johnfk3 - 8 months ago 31

Python Question

I have a list of tuples that looks something like this:

`tuples = [('a', 10, 11), ('b', 13, 14), ('a', 1, 2)]`

Is there a way that i can join them together based on the first index of every tuple to make a each tuple contain 5 elements. I know for a fact there isn't more that 2 of each letter in the tuples, Ie more than 2 'a's or 'b's in the entire list. The other requirement is to use Python2.6. I cant figure out the logic to it. Any help is greatly appreciated.

Desired Output:

`tuples = [('a', 10, 11, 1, 2), ('b', 13, 14, 0, 0)]`

I have tried creating a new list of first elements and adding the other elements to it but then I only have a list and not list of tuples.

EDIT to provide previous tried code,

Created a new list:

`templist, resultList = [], []`

Populate templist with the first element in every tuple:

`for i in tuples:`

templist.append(i[0])

elemlist = list(set(templist))

for i in elemlist:

for j in tuples:

if i == j[0]:

resultlist.append((i, j[1], j[2]))

This just returns the same list of tuples, How can i hold onto it and append every

`j[1] j[2]`

`j[0]`

Answer

Assuming there are only one or two of every letter in the list as stated:

```
import itertools
tuples = [('a', 10, 11), ('b', 13, 14), ('a', 1, 2)]
result = []
key = lambda t: t[0]
for letter,items in itertools.groupby(sorted(tuples,key=key),key):
items = list(items)
if len(items) == 1:
result.append(items[0]+(0,0))
else:
result.append(items[0]+items[1][1:])
print(result)
```

Output:

```
[('a', 10, 11, 1, 2), ('b', 13, 14, 0, 0)]
```