一個方法返回迭代器對象。 我想檢查要測試的數據的數量。如何從迭代器對象中獲取數字。 (Python2.7)
我認爲這是一個簡單的問題,但我並沒有解決它。
records = a_function()
self.assertEqual(1, len(records)) # TypeError: object of type 'listiterator' has no len()
Python2.7
一個方法返回迭代器對象。 我想檢查要測試的數據的數量。如何從迭代器對象中獲取數字。 (Python2.7)
我認爲這是一個簡單的問題,但我並沒有解決它。
records = a_function()
self.assertEqual(1, len(records)) # TypeError: object of type 'listiterator' has no len()
Python2.7
您需要將迭代器轉換到一個列表第一:
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)
[]
>>>
謝謝。它運行良好。 是,'records'是迭代器對象,這個名字是不適合的,我想。謝謝大家。 –
您可以輕鬆地
sum(1 for _ in it)
其中it
是要查找長度迭代器做到這一點。
這有點厚顏無恥:重複標記,然後發佈答案。但這次我會讓你擺脫它。 ;) –
;)。不會再重複 – Stormvirux
你的帖子中沒有期號。你對數據_有多少含義? – clemens