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
Solution 1:
[(tuple[a], tuple[a+1]) for a inrange(0,len(tuple),2)]
Solution 2:
Or, using itertools
(see the recipe for grouper
):
from itertools import izip
defgroup2(iterable):
args = [iter(iterable)] * 2return izip(*args)
tuples = [ab for ab in group2(tuple)]
Solution 3:
I present this code based on Peter Hoffmann's answer as a response to dfa's comment.
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.
The result of the method is going to be a list. This can be converted to tuples using the tuple()
function.
Sample:
definPairs(tup):
return [(tup[i], tup[i+1]) for i inrange(0, (len(tup)/2)*2, 2)]
# odd number of elementsprint("Odd Set")
odd = range(5)
print(odd)
po = inPairs(odd)
print(po)
# even number of elementsprint("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)]
Solution 4:
Here's a general recipe for any-size chunk, if it might not always be 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:
defiterchunk(iterable, n):
it= iter(iterable)
whileTrue:
chunk= []
try:
for i inrange(n):
chunk.append(it.next())
except StopIteration:
breakfinally:
iflen(chunk)!=0:
yieldtuple(chunk)
Post a Comment for "Multiple Tuple To Two-pair Tuple In Python?"