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
  • 159,742
  • 34
  • 281
  • 339
user596922
  • 1,501
  • 3
  • 18
  • 27

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
  • 9,125
  • 1
  • 29
  • 43
1

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

list(zip(c, c[len(c)//2:]))
blhsing
  • 91,368
  • 6
  • 71
  • 106
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
  • 159,742
  • 34
  • 281
  • 339