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

  • 本文关键字:python 调用 两个 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'}

iter返回的迭代器将仅从给定的可迭代对象中生成每个元素一次。您可以想象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首先会要求pnext元素,然后qnext元素 - 但只有一个迭代器 - 所以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)]

最后,当给定元组的可迭代对象时,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}

顺便说一下,这段代码是不必要的复杂:

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))

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

i2 = iter(a)

并且仍然得到相同的结果,b在这里是不必要的。

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

a = ['hello', 'world', '1', '2', 'other', 'thing']
c = dict(zip(a, a))

最新更新