小编Ner*_*uda的帖子

断言 Python 字典中所有值的数据类型的更好方法

我正在构建一个单元测试,断言/检查字典中的所有值是否具有相同的数据类型:float

Python版本3.7.4

假设我有四个不同的字典:

dictionary1: dict = {
    "key 1": 1.0,
}

dictionary2: dict = {
    "key 1": "1.0",
}

dictionary3: dict = {
    "key 1": 1.0,
    "key 2": 2.0,
    "key 3": 3.0
}

dictionary4: dict = {
    "key 1": "1",
    "key 2": "2",
    "key 3": 3
}
Run Code Online (Sandbox Code Playgroud)

以及这样的单元测试用例:

class AssertTypeUnitTest(unittest.TestCase):

    def test_value_types(self):
        dictionary: dict = dictionary
        self.assertTrue(len(list(map(type, (dictionary[key] for key in dictionary)))) is 1 and
                            list(map(type, (dictionary[key] for key in dictionary)))[0] is float)


if __name__ == "__main__":
    unittest.main() …
Run Code Online (Sandbox Code Playgroud)

python dictionary types unit-testing assertion

5
推荐指数
1
解决办法
7779
查看次数

标签 统计

assertion ×1

dictionary ×1

python ×1

types ×1

unit-testing ×1