I have a list of tuples like this one: L = [(23,56,48),(48,93,81),(48,56,23),(54,34,21),(48,98,71),(98,71,48),(56,23,48)]
Some of the tuples are having exactly the same numbers but in different order. I want to count the occurrences of the tuples and overwrite the ones that have the same values inside. I read several answers in here and I managed to do something using the Counter method. But what I tried doesn't seem to work for me. I am new at python so maybe I don't understand the exact use of Counter method.
L1 = Counter()
for item in L:
for element in item:
if element in item:
L1[tuple(item)] = L1[tuple(item)] + 1
print(L1)
The result I get is:
Counter({(23, 56, 48): 3, (48, 93, 81): 3, (48, 56, 23): 3, (54, 34, 21): 3,
(48, 98, 71): 3, (98, 71, 48): 3, (56, 23, 48): 3})
And the result I want to get is:
Counter({(23, 56, 48): 3, (48, 98, 71): 3, (48, 93, 81): 1, (54, 34, 21): 1})
You need to map the tuples with the same values to the same key , one way is sorting the tuples (using sorted ):
from collections import Counter
L = [(23,56,48),(48,93,81),(48,56,23),(54,34,21),(48,98,71),(98,71,48),(56,23,48)]
result = Counter(tuple(e) for e in map(sorted, L))
print(result)
Output
Counter({(23, 48, 56): 3, (48, 71, 98): 2, (21, 34, 54): 1, (48, 81, 93): 1})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.