Python程序员的逻辑任务。从列表中创建列表元组
我需要使用2个元素创建列表元组。Python程序员的逻辑任务。从列表中创建列表元组
例如,如果我有列表range(10)
我需要做的元组是这样的:
[(0,1),(2,3),(4,5),(6,7),(8,9)]
我如何能实现呢?
请参阅从itertools
文档的grouper recipe:
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)
这意味着,你可以这样做:
[(el[0], el[1]) for el in grouper(2, range(10))]
或者更一般地说:
[(el[0], el[1]) for el in grouper(2, elements)]
我会写列表(grouper(2,range(10))) – 2010-07-30 20:34:35
不错!我会记住的。 – 2010-07-30 20:45:10
许多不同的方式。只是为了炫耀几个:
为列表理解,其中l是一个序列(即整数索引):[(l[i], l[i+1]) for i in range(0,len(l),2)]
作为发电机的功能,适用于所有iterables:
def some_meaningful_name(it):
it = iter(it)
while True:
yield next(it), next(it)
天真通过名单切片(较大列表的糟糕表现)和复制,再次使用列表理解:[pair for pair in zip(l[::2],l[1::2])]
。
我喜欢第二好的,它可能是最pythonic和通用的(因为它是一个发电机,它运行在恒定的空间)。
也可以用做numpy:?多的元组两对元组在Python]
import numpy
elements = range(10)
elements = [tuple(e) for e in numpy.array(elements).reshape(-1,2).tolist()]
# [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
的可能重复(http://stackoverflow.com/questions/756550/multiple-tuple-to -two-pair-tuple-in-python) – 2010-07-30 20:09:45
duplicate:http://stackoverflow.com/questions/870652/pythonic-way-to-split-comma-separated-numbers-into-pairs/870677#870677 – FogleBird 2010-07-30 20:33:16
可能的重复[你如何在Python中将列表分割成大小均匀的块?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in -python) – tzot 2011-02-27 22:11:43