如何在python中将列表项重新排列为配对的元组/列表?

时间:2014-01-05 05:37:26

标签: python

我有一个形状列表

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

如何将其转换为

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

快? (清单很大。)

7 个答案:

答案 0 :(得分:6)

使用grouper recipe,它将处理奇怪的长度:

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)]

答案 1 :(得分:1)

我在考虑:

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)]

注意:

如果列表中的元素数量为奇数或偶数,则此方法有效。但如果它很奇怪,它将不会生成最后一个元素的元组:

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)]

答案 2 :(得分:0)

切片吧......不是那么难:

>>> 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)]

答案 3 :(得分:0)

假设该列表具有偶数个元素:
如果列表很大,你可以使用对生成器而不是列表(它会快得多)......

mylist = [1,2,3,4,5,6,7,8]
pairs = ((myList[i], myList[i+1]) for i in xrange(0, len(myList), 2))

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

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

答案 4 :(得分:0)

只需运行列表中的一个迭代器,每次抓取两个条目。 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. ...

答案 5 :(得分:0)

thefourtheye's answer中的列表理解将起作用。

另一种可能性是使用基于itertools模块的izip_longest函数的配方,详见this answer

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

pairs = map(tuple, grouper(2, [1,2,3,4,5,6,7,8]))
# [(1, 2), (3, 4), (5, 6), (7, 8)]

答案 6 :(得分:0)

如果列表是偶数或者您不关心奇数值,那么最简洁的方法是:

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