小编con*_*cia的帖子

使用unittest测试argparse-退出错误

要去关格雷格·哈斯在这个问题的答案,我试图让一个单元测试来检查当我通过它的一些ARGS不存在在该argparse是给相应的错误choices。但是,unittest使用以下try/except语句会产生误报。

另外,当我仅使用一条with assertRaises语句进行测试时,会argparse强制系统退出,并且程序不再执行任何其他测试。

我希望能够对此进行测试,但是鉴于argparse错误退出,也许这是多余的?

#!/usr/bin/env python3

import argparse
import unittest

class sweep_test_case(unittest.TestCase):
    """Tests that the merParse class works correctly"""

    def setUp(self):
        self.parser=argparse.ArgumentParser()
        self.parser.add_argument(
            "-c", "--color",
            type=str,
            choices=["yellow", "blue"],
            required=True)

    def test_required_unknown_TE(self):
        """Try to perform sweep on something that isn't an option.
        Should return an attribute error if it fails.
        This test incorrectly shows that the test passed, even though that must
        not be true."""
        args = …
Run Code Online (Sandbox Code Playgroud)

python unit-testing argparse python-3.x python-unittest

4
推荐指数
2
解决办法
2956
查看次数

什么是C++相当于python collections.Counter?

python collections.Counter对象跟踪对象的计数.

>> from collections import Counter
>> myC = Counter()
>> myC.update("cat")
>> myC.update("cat")
>> myC["dogs"] = 8
>> myC["lizards"] = 0
>> print(myC)
{"cat": 2, "dogs": 8, "lizards": 0}
Run Code Online (Sandbox Code Playgroud)

是否有类似的C++对象,我可以轻松跟踪类型的出现次数?也许是map为了string?请记住,上面只是一个例子,在C++中,这将推广到其他类型.

c++ python counter object equivalent

2
推荐指数
2
解决办法
640
查看次数

熊猫 getattr(df, "mean") 不像 df.mean() 那样工作

当我使用getattr()动态访问 Pandas 数据帧或系列的平均值时,它返回一个 Series.mean 对象。但是,当我df.mean()用来访问平均值时,它返回一个浮点数。

为什么不getattr()返回与普通方法相同的东西?

最小的可重现代码:

import pandas as pd
import numpy as np

s = pd.Series(np.random.randn(5))
print(getattr(s, "mean"))
>>> <bound method Series.mean of 
>>> 0    1.158042
>>> 1   -0.586821
>>> 2   -1.976764
>>> 3    1.722072
>>> 4    1.129570
print(s.mean())
>>> dtype: float64>
>>> 0.28921963496328584
Run Code Online (Sandbox Code Playgroud)

我曾经dir(getattr(s, "mean"))试图获得平均值,但无法弄清楚哪个属性(如果有)会让我获得浮点平均值。

python numpy dynamic pandas

0
推荐指数
1
解决办法
2120
查看次数