Python中将多元组转换为二元组?

12

最好的方法是如何拆分这个:

tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')

变成这样:

tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]

假设输入始终具有偶数个值。


7
您可能不希望使用名为"tuple"的变量,因为它会覆盖内置函数"tuple()"。 - recursive
5个回答

41

zip() 是你的好朋友:

t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip(t[::2], t[1::2])

1
+1 是因为它很漂亮,而且我不知道 [::] 语法。 - Steve B.
无法处理元组 = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i') # 注意最后的 'i',这使得元组长度为奇数 - dfa
@dfa:你说它不起作用是什么意思?如果输入长度为奇数,是否指定了新列表应该如何形成? - SilentGhost
哎呀,我刚刚读到了这句话:“假设输入始终具有偶数个值。” - dfa
如果输入元素的数量是奇数,那么剩下的元素应该怎么处理?它应该是一个单元素元组还是应该是 (x, None)?您必须根据预期的输出来调整输入。 - unbeknown

15
[(tuple[a], tuple[a+1]) for a in range(0,len(tuple),2)]

6

或者,使用 itertools(参见 grouperrecipe):

from itertools import izip
def group2(iterable):
   args = [iter(iterable)] * 2
   return izip(*args)

tuples = [ab for ab in group2(tuple)]

0

我根据Peter Hoffmann的回答编写了这段代码,作为对dfa的评论的回应。

无论你的元组是否具有偶数个元素,它都保证可以正常工作。

[(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)

输出

奇数集合
[0, 1, 2, 3, 4]
[(0, 1), (2, 3)]
偶数集合
[0, 1, 2, 3]
[(0, 1), (2, 3)]

-1

这里有一个通用的方案,适用于任何大小的块,如果它可能不总是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)

3
我认为你的意思是range(0, len(seq), n),而不是range(0, len(seq)。 - Noah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接