首先,你的书是错的(或者你误解了):
First of all, your book is wrong (or you've misunderstood it):
>>> dict([(1, 2), (3, 4), (5, 6)])
{1: 2, 3: 4, 5: 6}
如您所见, dict([
列表元组
])
返回Python 2.x和3.x中的字典。
As you can see, dict([
list of tuples
])
returns a dictionary in both Python 2.x and 3.x.
列表和迭代器之间的根本区别在于列表包含特定顺序的多个对象 - 所以你可以,例如,从某个地方拉出其中一个在中间:
The fundamental difference between a list and an iterator is that a list contains a number of objects in a specific order - so you can, for instance, pull one of them out from somewhere in the middle:
>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list[3]
'd'
...而迭代器收益率按特定顺序排列的多个对象,通常按要求动态创建:
... whereas an iterator yields a number of objects in a specific order, often creating them on the fly as requested:
>>> 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循环遍历迭代器更常见:
I'm using next()
here for demonstration purposes; in real code it's more common to iterate over an iterator with a for loop:
for x in my_iter:
# do something with x
注意权衡:一万亿个整数的列表会占用更多的内存而不是大多数机器都可用,这使得迭代器更加高效......代价是无法在中间某处询问对象:
Notice the trade-off: a list of a trillion integers would use more memory than most machines have available, which makes the iterator much more efficient ... at the cost of not being able to ask for an object somewhere in the middle:
>>> my_iter[37104]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'range_iterator' object is not subscriptable