将列表中的每一对元素收集到 Python 中的元组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4647050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:44:34  来源:igfitidea点击:

Collect every pair of elements from a list into tuples in Python

python

提问by TartanLlama

Possible Duplicate:
Pairs from single list

可能的重复:
来自单个列表的对

I have a list of small integers, say:

我有一个小整数列表,比如:

[1, 2, 3, 4, 5, 6]

I wish to collect the sequential pairs and return a new list containing tuples created from those pairs, i.e.:

我希望收集顺序对并返回一个包含从这些对创建的元组的新列表,即:

[(1, 2), (3, 4), (5, 6)]

I know there must be a really simple way to do this, but can't quite work it out.

我知道必须有一个非常简单的方法来做到这一点,但不能完全解决。

Thanks

谢谢

采纳答案by Skurmedel

Well there is one very easy, but somewhat fragile way, zip it with sliced versions of itself.

嗯,有一种非常简单但有点脆弱的方法,用它自己的切片版本压缩它。

zipped = zip(mylist[0::2], mylist[1::2])

In case you didn't know, the last slice parameter is the "step". So we select every second item in the list starting from zero (1, 3, 5). Then we do the same but starting from one (2, 4, 6) and make tuples out of them with zip.

如果您不知道,最后一个切片参数是“步骤”。因此,我们从零 (1, 3, 5) 开始选择列表中的每第二个项目。然后我们做同样的事情,但从一 (2, 4, 6) 开始,用zip.

回答by Jim Brissom

Straight from the Python documentation of the itertoolsmodule:

直接来自itertools模块的 Python 文档:

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

l = [1, 2, 3, 4, 5, 6]
for pair in pairwise(l):
    print pair

回答by Senthil Kumaran

Apart from the above answers, you also need to know the simplest of way too (if you hadn't known already)

除了上面的答案,你还需要知道最简单的方法(如果你还不知道的话)

l = [1, 2, 3, 4, 5, 6]
o = [(l[i],l[i+1]) for i in range(0,len(l),2)]