[英]why the zip function did not give the expected result in python
a = enumerate('abcdef')
b = enumerate('ghi')
for i, j in zip(a, b):
print(i, j)
if i[0] == 0:
next(itertools.islice(zip(a, b), 1, 1), None)
For the above code, I expect the following result as I advance zip(a, b) by 1: 对于上面的代码,当我将zip(a,b)提前1时,我期望得到以下结果:
((0, 'a'), (0, 'g'))
((2, 'c'), (2, 'i'))
However, it still gives the same result as the following code: 但是,它仍然提供与以下代码相同的结果:
iter1 = enumerate('abcdef')
iter2 = enumerate('ghi')
for i, j in zip(a, b):
print(i, j)
output: 输出:
((0, 'a'), (0, 'g'))
((1, 'b'), (1, 'h'))
((2, 'c'), (2, 'i'))
why the statement next(itertools.islice(zip(a, b), 1, 1), None) does not advance zip(a, b)? 为什么语句next(itertools.islice(zip(a,b),1,1),None)不推进zip(a,b)?
The 3.6 zip returns iterators and it works as you expect: 3.6 zip返回迭代器,它可以按预期工作:
a = enumerate('abcdef')
b = enumerate('ghi')
for i, j in zip(a, b):
print(i, j)
if i[0] == 0:
next(itertools.islice(zip(a, b), 1, 1), None)
it will skip the (1,)
tuples as zip returns iterators. 当zip返回迭代器时
(1,)
它将跳过(1,)
元组。
The 2.7 zip returns a list of tuples, and both statements are unrelated as the zip(a,b)
are seperate list, both using unrelated enumeration sequences. 2.7 zip返回一个元组列表,并且两个语句都不相关,因为
zip(a,b)
是单独的列表,都使用不相关的枚举序列。
So for 2.7 they are not skipping the (1,)
tuples. 因此,对于2.7,它们不会跳过
(1,)
元组。
Output 3.6: 输出3.6:
(0, 'a') (0, 'g')
(2, 'c') (2, 'i')
Output 2.7: 输出2.7:
((0, 'a'), (0, 'g'))
((1, 'b'), (1, 'h'))
((2, 'c'), (2, 'i'))
You are running 2.7 from your demo output. 您正在从演示输出中运行2.7。
https://docs.python.org/3.6/library/functions.html#zip https://docs.python.org/2.7/library/functions.html#zip https://docs.python.org/3.6/library/functions.html#zip https://docs.python.org/2.7/library/functions.html#zip
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.