方法返回迭代器对象。 我想检查要测试的数据的数量。
我认为这是一个简单的问题,但我不能解决它。
records = a_function()
self.assertEqual(1, len(records)) # TypeError: object of type 'listiterator' has no len()
Python2.7
答案 0 :(得分:6)
您需要先将迭代器转换为列表:
len(list(records))
请参阅:
>>> some_list = [1, 2, 3, 4, 5]
>>> it = iter(list)
>>> it = iter(some_list)
>>> len(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'list_iterator' has no len()
>>> len(list(it))
5
>>>
但请注意,这将使用迭代器:
>>> list(it)
[]
>>>
答案 1 :(得分:2)
您可以通过
轻松完成sum(1 for _ in it)
其中it
是您想要查找长度的迭代器。