Active October 10, 2021 / Viewed 1040 / Comments 0 / Edit

Examples of how to find the number of occurrences in a list of tuples in python :

Let's create a list of tuples:

`mylist = [`

`('a', 'b', 'c',),`

`('a', 'b', 'c',),`

`('c', 'b', 'a',),`

`('a', 'b', ),`

`('a',)`

`]`

note that

`type(mylist)`

`type(mylist[0])`

gives

`<class 'list'>`

and

`<class 'tuple'>`

respectively

To find occurrences of tuples in a list, a solution is to use counter from collections

`from collections import Counter`

`counter = Counter(e for e in mylist)`

gives

`Counter({('a', 'b', 'c'): 2, ('c', 'b', 'a'): 1, ('a', 'b'): 1, ('a',): 1})`

Note that here ('a', 'b', 'c') and ('c', 'b', 'a') are considered as different tuples.

Also it is possible to put counter results in a dictionary:

`d = dict( counter )`

`print( d )`

`print( d.keys() )`

`print( d[('a', 'b', 'c')] )`

gives

`{('a', 'b', 'c'): 2, ('c', 'b', 'a'): 1, ('a', 'b'): 1, ('a',): 1}`

`dict_keys([('a', 'b', 'c'), ('c', 'b', 'a'), ('a', 'b'), ('a',)])`

`2`

Another example, find occurrences of tuples that contains same elements. So ('a', 'b', 'c') == ('c', 'b', 'a')

`from collections import Counter`

`counter = Counter(tuple(sorted(t)) for t in mylist)`

`print(counter)`

gives

`Counter({('a', 'b', 'c'): 3, ('a', 'b'): 1, ('a',): 1})`

To find only occurrences of elements in each tuple, a solution is to do:

`import itertools`

`mylist2 = list(itertools.chain.from_iterable(mylist) )`

`print(mylist2)`

gives

`['a', 'b', 'c', 'a', 'b', 'c', 'c', 'b', 'a', 'a', 'b', 'a']`

`print( Counter(mylist2) )`

gives

`Counter({'a': 5, 'b': 4, 'c': 3})`

Note: to get only unique elements:

`mylist2 = list( set(itertools.chain.from_iterable(mylist)) )`

`print(mylist2)`

gives

`['c', 'a', 'b']`

Ads

License

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Ads

Ads