1

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?

jpp
  • 147,904
  • 31
  • 244
  • 302
user596922
  • 1,391
  • 2
  • 16
  • 25

3 Answers3

1

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.

asthasr
  • 8,804
  • 1
  • 28
  • 39
1

You can slice the list at mid point and then zip with the list itself:

list(zip(c, c[len(c)//2:]))
blhsing
  • 77,832
  • 6
  • 59
  • 90
0

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')]
jpp
  • 147,904
  • 31
  • 244
  • 302