1

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' ?

EbraHim
  • 2,279
  • 2
  • 16
  • 28
S.P
  • 11
  • 2
  • Take a look at this: http://stackoverflow.com/questions/11697709/comparing-two-lists-in-python – Edward Apr 25 '16 at 03:16

2 Answers2

1

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')]
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

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
>>> 
EbraHim
  • 2,279
  • 2
  • 16
  • 28