gpt4 book ai didi

python - 一次迭代列表中的每 2 个元素

转载 作者:太空狗 更新时间:2023-10-29 20:33:03 26 4
gpt4 key购买 nike

列表为

l = [1,2,3,4,5,6,7,8,9,0]

如何一次迭代每两个元素?

我正在尝试,

for v, w in zip(l[:-1],l[1:]):
print [v, w]

得到的输出就像,

[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
[9, 0]

预期输出是

[1,2]
[3, 4]
[5, 6]
[7, 8]
[9,10]

最佳答案

你可以使用iter:

>>> seq = [1,2,3,4,5,6,7,8,9,10]
>>> it = iter(seq)
>>> for x in it:
... print (x, next(it))
...
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]

您还可以使用 grouper recipe来自 itertools:

>>> from itertools import izip_longest
>>> def grouper(iterable, n, fillvalue=None):
... "Collect data into fixed-length chunks or blocks"
... # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
... args = [iter(iterable)] * n
... return izip_longest(fillvalue=fillvalue, *args)
...
>>> for x, y in grouper(seq, 2):
... print (x, y)
...
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]

关于python - 一次迭代列表中的每 2 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21752610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com