我在网上找到了下面的代码,结果是列表中两个元素的元组,如何理解[iter(list)]*2
?
lst = [1,2,3,4,5,6,7,8]
b=zip(*[iter(lst)]*2)
list(b)
[(1, 2), (3, 4), (5, 6), (7, 8)]
------------
[iter(lst)]*2
[<list_iterator at 0x1aff33917f0>, <list_iterator at 0x1aff33917f0>]
我查了
[iter(lst)]*2
,与上面相同的迭代器,所以意思是 iter
重复双倍,所以,如果我检查 num 从 2 到 3,结果应该是
[(1, 2, 3), (4, 5, 6),(7,8,NaN)]
但删除 7,8lst = [1,2,3,4,5,6,7,8]
b=zip(*[iter(lst)]*3)
list(b)
--------------
[(1, 2, 3), (4, 5, 6)]
最佳答案
解释起来相当棘手。我试一试:
与 [iter(lst)]
您创建一个包含一项的列表。该项目是一个列表的迭代器。
每当 python 试图从这个迭代器中获取一个元素时,就会得到 lst
的下一个元素。返回直到没有更多元素可用。
只需尝试以下操作:
i = iter(lst)
next(i)
next(i)
输出应如下所示:>>> lst = [1,2,3,4,5,6,7,8]
>>> i = iter(lst)
>>> next(i)
1
>>> next(i)
2
>>> next(i)
3
>>> next(i)
4
>>> next(i)
5
>>> next(i)
6
>>> next(i)
7
>>> next(i)
8
>>> next(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
现在您创建了一个包含两次 的列表。完全一样迭代器。你这样做
itlst = [iter(lst)] * 2
尝试以下操作:itlst1 = [iter(lst)] * 2
itlst2 = [iter(lst), iter(lst)]
print(itlst1)
print(itlst2)
结果将类似于:>>> itlst1 = [iter(lst)] * 2
>>> itlst2 = [iter(lst), iter(lst)]
>>> print(itlst1)
[<list_iterator object at 0x7f9251172b00>, <list_iterator object at 0x7f9251172b00>]
>>> print(itlst2)
[<list_iterator object at 0x7f9251172b70>, <list_iterator object at 0x7f9251172ba8>]
需要注意的是,itlst1
是一个包含两次相同迭代器的列表,而 itlst2
包含两个不同的迭代器。为了说明尝试键入:
next(itlst1[0])
next(itlst1[1])
next(itlst1[0])
next(itlst1[1])
并将其与:next(itlst2[0])
next(itlst2[1])
next(itlst2[0])
next(itlst2[1])
结果是:>>> next(itlst1[0])
1
>>> next(itlst1[1])
2
>>> next(itlst1[0])
3
>>> next(itlst1[1])
4
>>>
>>> next(itlst2[0])
1
>>> next(itlst2[1])
1
>>> next(itlst2[0])
2
>>> next(itlst2[1])
2
现在到 zip()
功能( https://docs.python.org/3/library/functions.html#zip ):尝试以下操作:
i = iter(lst)
list(zip(i, i))
zip()
带两个参数。每当您尝试从
zip
获取下一个元素时它将执行以下操作:list(zip(xxx))
将重复执行此操作并将结果存储在列表中。结果将是:
>>> i = iter(lst)
>>> list(zip(i, i))
[(1, 2), (3, 4), (5, 6), (7, 8)]
使用的下一个技巧是 *
用于将第一个元素用作函数调用的第一个参数,将第二个元素用作第二个参数,依此类推)What does ** (double star/asterisk) and * (star/asterisk) do for parameters?所以写:
itlst1 = [iter(lst)] * 2
list(zip(*itlst1))
在这种情况下与i = iter(lst)
itlst1 = [i] * 2
list(zip(itlst1[0], itlst1[1]))
这与list(zip(i, i))
我已经解释过了。希望这可以解释上述大部分技巧。
关于python - python中[iter(list)]*2的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61670945/