Vijay
Vijay

Reputation: 1825

Generating tuple from a list of items in Python

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

Answers (3)

jpp
jpp

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

blhsing
blhsing

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

asthasr
asthasr

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

Related Questions