为什么这两个调用在python中有所不同?

时间:2017-07-26 18:42:42

标签: python

我刚刚开始使用python,但我可以理解为什么要调用它会得到不同的结果

from itertools import izip
a =  ['hello','world','1','2', 'other', 'thing']
b =  ['hello','world','1','2', 'other', 'thing']
i = iter(a)
i2= iter(b)
c = dict(izip(i, i2))

结果:

{'thing': 'thing', '1': '1', 'other': 'other', '2': '2', 'world': 'world', 'hello': 'hello'}
from itertools import izip
a =  ['hello','world','1','2', 'other', 'thing']
i = iter(a)
c = dict(izip(i, i))

结果:

{'1': '2', 'other': 'thing', 'hello': 'world'}

1 个答案:

答案 0 :(得分:2)

iter返回的迭代器只会从给定的iterable中生成一个元素。您可以想象iter返回的每个迭代器,就好像有一个指向下一个元素的符号。在第一段摘录中,您有2个符号:ii2,而第二个只有一个。迭代器支持一个名为next的操作,该操作将获得"签署"指向当前,并移动"标志"所以它指向以下元素。

zip(p, q) / izip(p, q)将在内部从p获取下一个元素,然后从q获取并构建这些元素的元组,并将其生成;然后重复,只要pq都有next元素。

在第一种情况下,有2个独立的迭代器。因此,ii2都会产生各自列表中的所有元素。我将使用更简单的代码和zip来呈现它 - 作为奖励,这是与Python 3兼容的:

>>> a = [1, 2, 3, 4]
>>> p = iter(a)
>>> q = iter(a)
>>> list(zip(p, q))
[(1, 1), (2, 2), (3, 3), (4, 4)]

在第二种情况下,您两次传入相同的迭代器。 izip仍然认为它有2个迭代器;因此izip首先会向p询问next元素,然后q询问next元素 - 但只有一个迭代器 - 所以{{1将会看到每个第二个元素来自izip,而每秒来自p

q

最后,>>> a = [1, 2, 3, 4] >>> p = iter(a) >>> q = p >>> q is p True >>> list(zip(p, q)) [(1, 2), (3, 4)] ,当给出元组的 iterable 时,将构造一个字典,每个元组的第一个元素成为一个键,第二个元素成为该键的值。因此:

dict

>>> dict([(1, 1), (2, 2), (3, 3), (4, 4)])
{1: 1, 2: 2, 3: 3, 4: 4}

顺便说一句,这段代码不必要地复杂化了:

>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}

首先,列表不需要重复 - 你可以在同一个列表上迭代2个迭代器,它们可以独立工作,即你可以拥有

a = ['hello', 'world', '1', '2', 'other', 'thing']
b = ['hello', 'world', '1', '2', 'other', 'thing']
i = iter(a)
i2= iter(b)
c = dict(izip(i, i2))

仍然得到相同的结果,i2 = iter(a) 在这里是不必要的。

其次,大多数时候你不需要显式创建迭代器 - 隐式会这样做。因此,第一种情况的代码可以简单地写成

b
相关问题