如何在python中将列表项重新设置为成对的元组/列表?

如何在python中将列表项重新设置为成对的元组/列表?,python,Python,我有一个形状列表 [1,2,3,4,5,6,7,8] 我怎样才能把它变成 [(1,2),(3,4),(5,6),(7,8)] 快点?(列表很大。)我在想: a = [1, 2, 3, 4, 5, 6, 7, 8] print [(a[i], a[i + 1]) for i in xrange(0, len(a) - 1, 2)] 输出: [(1, 2), (3, 4), (5, 6), (7, 8)] [(1, 2), (3, 4), (5, 6), (7, 8)] 注意: [(1,

我有一个形状列表

[1,2,3,4,5,6,7,8]
我怎样才能把它变成

[(1,2),(3,4),(5,6),(7,8)]
快点?(列表很大。)

我在想:

a = [1, 2, 3, 4, 5, 6, 7, 8]
print [(a[i], a[i + 1]) for i in xrange(0, len(a) - 1, 2)]
输出:

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

注意:

[(1, 2), (3, 4), (5, 6), (7, 8)]
[(1, 2), (3, 4), (5, 6), (7, 8)]
如果列表中的元素数为奇数或偶数,则此操作有效。但如果是奇数,则不会生成包含最后一个元素的元组:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print [(a[i], a[i + 1]) for i in xrange(0, len(a) - 1, 2)]
输出:

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

把它切成薄片。。。没那么难:

>>> l = [1,2,3,4,5,6,7,8]
>>> r = []
>>> for i in range(0, len(l), 2):
        r.append(tuple(l[i:i+2]))


>>> print(r)
[(1, 2), (3, 4), (5, 6), (7, 8)]
或较短的LC版本:

r = [tuple(l[i:i+2]) for i in range(0, len(l), 2)]

假设列表中有偶数个元素:
如果列表很大,您可以使用pairs生成器而不是列表(速度会快得多)

如果你必须有一个结果列表-使用其他答案中建议的列表理解

[(myList[i], myList[i+1]) for i in xrange(0, len(myList), 2)]

只需运行列表的一个迭代器,每次获取两个条目
zip
可以让您很好地完成此操作

from itertools import izip_longest
# assuming you are on Python 2
# if you are on Python 3 this is zip_longest

your_list = range(22)

# First, make an iterator for the list
iterator = iter(your_list)

# Then grab two entries from the iterator
# each iteration (using zip, but you could also
# use x, y = next(iterator), next(iterator)
# if you wanted to be *really* explicit.
results = izip_longest(iterator, iterator)
for val in results:
    print val

# (0, 1)
# (2, 3)
# (4, 5)
# ... etc. ...
中的列表将起作用

另一种可能是使用基于
itertools
模块的
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)
像这样使用它:

>>> from itertools import izip_longest # needed for grouper helper
>>> list(grouper([1,2,3,4,5,6,7], 2))
[(1, 2), (3, 4), (5, 6), (7, None)]

如果列表为偶数或不关心奇数,有一种最简洁的方法:

x = range(10)
zip(x[::2], x[1::2])
或者如果列表是单数:

import itertools as it

x = range(11)
list(it.izip_longest(x[::2], x[1::2], fillvalue=x[-1]+1))
或者,如果不想在内存中创建列表,请使用完整的迭代器方式:

import itertools as it

x = xrange(10000001) # Or really long, maybe infinite iterator
pg = it.izip_longest(it.islice(x,0,None,2), it.islice(x,1,None,2), fillvalue=10000000000)
for pair in pg:
    print pair

如果列表中没有偶数个元素怎么办?在我的用例中,输入数据首先被过滤/检查为偶数。答案处理列表中的奇数肯定是受欢迎的。可能重复@PlatinumAzure,但您的答案是通用的:)切片将创建一个新列表,理解速度将快于变异。:)