Question

I have a list of tuples that look like this.

[(1,2),(3,4),(2,1),(1,2),(2,3),(2,3)]

I want the output that looks like this.

[(1,2,2),(3,4,1),(2,1,1),(2,3,2)]

The third value in the tuple is the number of times the tuple occurs in the list.

What is an efficient way to iterate list of tuple and add value at the end of the tuple? Thanks.

Was it helpful?

Solution

data = [(1, 2), (3, 4), (2, 1), (1, 2), (2, 3), (2, 3)]
from collections import Counter, OrderedDict

# Use Counter to find the number of times the tuple occured
d = Counter(data)

# Use OrderedDict to maintain the order of occurance
# Get tuples from OrderedDict and get count from d, create a new tuple
print [item + (d[item],) for item in OrderedDict.fromkeys(data)]
# [(1, 2, 2), (3, 4, 1), (2, 1, 1), (2, 3, 2)]

OTHER TIPS

Here is the correct code:

>>> lst = [(1,2), (3,4), (2,1), (1,2), (2,3), (2,3)]
>>> def count(tuple, list):
...     num = 0
...     for k in list:
...             if sorted(k) == sorted(tuple):
...                     num+=1
...     return num
... 
>>> count((1, 2), lst)
3
>>> newlst = []
>>> for k in lst:
...     num = count(k, lst)
...     new = k+(num,)
...     if new not in newlst:
...             newlst.append(new)
... 
>>> newlst
[(1, 2, 3), (3, 4, 1), (2, 1, 3), (2, 3, 2)]
>>> 

I used a set to determine all the unique entries. Then I iterated through each item in the set and counted the number of occurrences of that tuple in the original list and created a new tuple with the original tuple combined with the count.

>>> data = [(1,2),(3,4),(2,1),(1,2),(2,3),(2,3)]
>>> unique = set(data)
>>> count = [t + (data.count(t),) for t in unique]
>>> count
[(1, 2, 2), (2, 3, 2), (3, 4, 1), (2, 1, 1)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top