Reputation: 1825
I;m trying to generate a tuple list from a larger list. how do I do it in pythonic way?
c = ['A1','B1','C1','A2','B2','C2']
Output required is something like this:
c = [('A1','A2'),('B1','B2'),('C1','C2')]
I tried to iterate through the list and put a regex to match for mattern and then added that to a tuple but that doesn;t look convincing for me.. Any better way to handle this?
Upvotes: 1
Views: 111
Reputation: 164843
With no assumption on ordering or size of each tuple, you can use collections.defaultdict
. This does assume your letters are in range A-Z.
from collections import defaultdict
dd = defaultdict(list)
c = ['A1','B1','C1','A2','B2','C2']
for i in c:
dd[i[:1]].append(i)
res = list(map(tuple, dd.values()))
print(res)
[('A1', 'A2'), ('B1', 'B2'), ('C1', 'C2')]
Upvotes: 0
Reputation: 107124
You can slice the list at mid point and then zip with the list itself:
list(zip(c, c[len(c)//2:]))
Upvotes: 1
Reputation: 9427
If the length is exactly the same, you can do this:
half = len(c) / 2
pairs = zip(c[:half], c[half:])
zip
accepts two lists and returns a list of pairs. The slices refer to the first half of the list and the second half, respectively.
Upvotes: 1