首先,你的书是错的(或者你误解了它):
>>> dict([(1, 2), (3, 4), (5, 6)])
{1: 2, 3: 4, 5: 6}
如您所见,dict([list of tuples]) 在 Python 2.x 和 3.x 中都返回一个字典。
列表和迭代器之间的根本区别在于列表包含许多按特定顺序排列的对象 - 例如,您可以从中间的某处拉出其中一个:
>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list[3]
'd'
...而迭代器产生以特定顺序的多个对象,通常根据要求动态创建它们:
>>> my_iter = iter(range(1000000000000))
>>> my_iter
<range_iterator object at 0x7fa291c22600>
>>> next(my_iter)
0
>>> next(my_iter)
1
>>> next(my_iter)
2
我在这里使用next() 进行演示;在实际代码中,使用 for 循环遍历迭代器更为常见:
for x in my_iter:
# do something with x
注意权衡:一万亿个整数的列表将使用比大多数机器可用的内存更多的内存,这使得迭代器更加高效......但代价是无法在中间:
>>> my_iter[37104]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'range_iterator' object is not subscriptable