Reputation: 11
I have 2 lists,
list1 = ['a', 'b', 'c', 'a']
list2 = ['A', 'B', 'C', 'D','A']
How can I find the frequency for each combinations of 'a''A'
, 'b''B'
and 'c''C'
?
Upvotes: 1
Views: 198
Reputation: 2349
The other answer is okay, but it needs list1
and list2
to be sorted and to have equal number of each letter.
Below program works for all cases:
from string import ascii_lowercase
list1 = ['a', 'b', 'c', 'a']
list2 = ['A', 'B', 'C', 'D','A']
for letter in ascii_lowercase:
if letter in list1 and letter.capitalize() in list2:
n1 = list1.count(letter)
n2 = list2.count(letter.capitalize())
print letter,'-',letter.capitalize(), min(n1,n2)
Output:
>>> ================================ RESTART ================================
>>>
a - A 2
b - B 1
c - C 1
>>>
Upvotes: 0
Reputation: 174624
Use the aptly named Counter
, from collections
, like this:
>>> from collections import Counter
>>> Counter(zip(['a','b','c','a'],['A','B','C','A'])).most_common()
[(('a', 'A'), 2), (('b', 'B'), 1), (('c', 'C'), 1)]
zip
quickly creates the pairs of objects that should be compared:
>>> zip(['a','b','c','a'],['A','B','C','A'])
[('a', 'A'), ('b', 'B'), ('c', 'C'), ('a', 'A')]
Upvotes: 1