Python元组重组

Python元组重组,python,tuples,Python,Tuples,我对python有点陌生,目前正努力以我想要的方式返回元组列表 如果我有一个元组列表 [('a',),('b',),('c',),('d',),('e',),('f',)] 我怎样才能把它改成 [('a','b'),('c','d'),('e','f')] 或 有没有一种简单的方法来重组元组 任何帮助都将不胜感激。要获得长度一致的内部元组,您可以通过itertools.chain展平元组列表,然后定义分块生成器: from itertools import chain L = [(

我对python有点陌生,目前正努力以我想要的方式返回元组列表

如果我有一个元组列表

  [('a',),('b',),('c',),('d',),('e',),('f',)]
我怎样才能把它改成

  [('a','b'),('c','d'),('e','f')]

有没有一种简单的方法来重组元组

任何帮助都将不胜感激。

要获得长度一致的内部元组,您可以通过
itertools.chain
展平元组列表,然后定义分块生成器:

from itertools import chain

L = [('a',),('b',),('c',),('d',),('e',),('f',)]

def chunker(L, n):
    T = tuple(chain.from_iterable(L))
    for i in range(0, len(L), n):
        yield T[i: i+n]

res_2 = list(chunker(L, 2))  # [('a', 'b'), ('c', 'd'), ('e', 'f')]
res_3 = list(chunker(L, 3))  # [('a', 'b', 'c'), ('d', 'e', 'f')]
res_4 = list(chunker(L, 4))  # [('a', 'b', 'c', 'd'), ('e', 'f')]

否则,您需要首先定义逻辑以确定每个元组的大小。

您可以将
zip
与适当的切片一起使用:

l = [('a',),('b',),('c',),('d',),('e',),('f',)]

[x+y for x, y in zip(l[::2], l[1::2])]
# [('a', 'b'), ('c', 'd'), ('e', 'f')]

使用来自以下地址的石斑鱼:

如何使用?

>>> list(grouper(2, chain.from_iterable(lst)))
[('a', 'b'), ('c', 'd'), ('e', 'f')]
>>> list(grouper(3, chain.from_iterable(lst)))
[('a', 'b', 'c'), ('d', 'e', 'f')]
from itertools import chain, zip_longest

lst = [('a',),('b',),('c',),('d',),('e',),('f',)]

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)
>>> list(grouper(2, chain.from_iterable(lst)))
[('a', 'b'), ('c', 'd'), ('e', 'f')]
>>> list(grouper(3, chain.from_iterable(lst)))
[('a', 'b', 'c'), ('d', 'e', 'f')]