简体   繁体   English

Python中的多元组到双组元组?

[英]Multiple Tuple to Two-Pair Tuple in Python?

What is the nicest way of splitting this: 拆分这个最好的方法是什么:

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

into this: 进入这个:

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

Assuming that the input always has an even number of values. 假设输入始终具有偶数个值。

zip() is your friend: zip()是你的朋友:

t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip(t[::2], t[1::2])
[(tuple[a], tuple[a+1]) for a in range(0,len(tuple),2)]

Or, using itertools (see the recipe for grouper ): 或者,使用itertools (参见grouper配方 ):

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

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

I present this code based on Peter Hoffmann's answer as a response to dfa's comment . 我根据Peter Hoffmann的答案提出这个代码作为对dfa评论的回应

It is guaranteed to work whether or not your tuple has an even number of elements. 无论你的元组是否具有偶数个元素,它都可以保证工作。

[(tup[i], tup[i+1]) for i in range(0, (len(tup)/2)*2, 2)]

The (len(tup)/2)*2 range parameter calculates the highest even number less or equal to the length of the tuple so it is guaranteed to work whether or not the tuple has an even number of elements. (len(tup)/2)*2范围参数计算小于或等于元组长度的最高偶数,因此无论元组是否具有偶数个元素,它都可以保证工作。

The result of the method is going to be a list. 该方法的结果将是一个列表。 This can be converted to tuples using the tuple() function. 这可以使用tuple()函数转换为元tuple()

Sample: 样品:

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)

Output 产量

Odd Set
[0, 1, 2, 3, 4]
[(0, 1), (2, 3)]
Even Set
[0, 1, 2, 3]
[(0, 1), (2, 3)]

Here's a general recipe for any-size chunk, if it might not always be 2: 这是任意大小的块的一般配方,如果它可能不总是2:

def chunk(seq, n):
    return [seq[i:i+n] for i in range(0, len(seq), n)]

chunks= chunk(tuples, 2)

Or, if you enjoy iterators: 或者,如果您喜欢迭代器:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM