什么是这个分裂的最好的方式:假定输入总是有偶数个值Python中的多元组到两对元组?
tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
:
tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
到这一点。
什么是这个分裂的最好的方式:假定输入总是有偶数个值Python中的多元组到两对元组?
tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
:
tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
到这一点。
zip()
是你的朋友:
t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip(t[::2], t[1::2])
不错的选择! – 2009-04-16 15:13:59
+1,因为它很漂亮,我不知道[::]语法 – 2009-04-16 15:14:53
不适用于tuple =('a','b','c','d','e','f ','g','h','i')#注意最后的'i',这使得元组奇数长度 – dfa 2009-04-16 17:12:49
[(tuple[a], tuple[a+1]) for a in range(0,len(tuple),2)]
+1更明确的使用范围功能 – 2009-04-16 15:09:32
这里有一个一般的配方任何大小的块,如果它可能并不总是2:
def chunk(seq, n):
return [seq[i:i+n] for i in range(0, len(seq), n)]
chunks= chunk(tuples, 2)
或者,如果你喜欢的迭代器:
def iterchunk(iterable, n):
it= iter(iterable)
while True:
chunk= []
try:
for i in range(n):
chunk.append(it.next())
except StopIteration:
break
finally:
if len(chunk)!=0:
yield tuple(chunk)
或者,我们荷兰国际集团itertools
(见recipegrouper
为):
from itertools import izip
def group2(iterable):
args = [iter(iterable)] * 2
return izip(*args)
tuples = [ab for ab in group2(tuple)]
我提出了基于Peter Hoffmann's answer此代码为dfa's comment的响应。
无论您的元组是否具有偶数个元素,它都能保证正常工作。
[(tup[i], tup[i+1]) for i in range(0, (len(tup)/2)*2, 2)]
的(len(tup)/2)*2
范围参数计算最高偶数小于或等于元组的长度,以便它是保证工作的元组是否具有偶数个元件。
该方法的结果将成为一个列表。这可以使用tuple()
函数转换为元组。
样品:
def inPairs(tup):
return [(tup[i], tup[i+1]) for i in range(0, (len(tup)/2)*2, 2)]
# odd number of elements
print("Odd Set")
odd = range(5)
print(odd)
po = inPairs(odd)
print(po)
# even number of elements
print("Even Set")
even = range(4)
print(even)
pe = inPairs(even)
print(pe)
输出
Odd Set [0, 1, 2, 3, 4] [(0, 1), (2, 3)] Even Set [0, 1, 2, 3] [(0, 1), (2, 3)]
你可能不希望一个名为元组变量,它将覆盖内置函数元组()。 – recursive 2009-04-16 15:55:44