S Ringne - 1 year ago 109
Python Question

# Frequency of a list of tuples

I have a list:

``````a = [(['7', '8'], ['4', '7'],['3', '4'],['3', '8'],['4', '8'],...............['3','4'])]
``````

I want to create 2 columns which give me the frequency of the tuples in the list. For example:

``````bigram      frequency
['7','8']     2
['4','7']     3
['3', '4']    6
``````

and so on.

And also, consider entries like
`['7','8']`
and
`['8','7']`
the same (duplicates). The only one entry should be in the column and frequency should be added to that.

I was trying to use

``````from collections import counter
``````

and do some loop over it, but I was getting error as:

unhashable type: list

try this:

``````from collections import Counter

a = [(['7', '8'], ['4', '7'],['3', '4'],['3', '8'],['4', '8'],['3','4'],['7','8'],['8','7'],['4','3'])]

frequency_list = Counter(tuple(sorted(i)) for i in a[0])

print "bigram","frequency"
for key,val in frequency_list.items():
print key, val
``````

output is as follows

``````bigram    frequency
('4', '7') 1
('4', '8') 1
('7', '8') 3
('3', '4') 3
('3', '8') 1
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download