2016-04-25 30 views
1

我有2个清单,Python中找到组合的频率在2所列出

list1 = ['a', 'b', 'c', 'a'] 
list2 = ['A', 'B', 'C', 'D','A'] 

我怎样才能找到的'a''A''b''B''c''C'每个组合的频率是多少?

+0

看看这个:http://stackoverflow.com/questions/11697709/comparing-two-lists- in-python – Edward

回答

1

使用恰当地命名为Counter,从collections,像这样:

>>> 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快速创建的对象的对应该比较:

>>> zip(['a','b','c','a'],['A','B','C','A']) 
[('a', 'A'), ('b', 'B'), ('c', 'C'), ('a', 'A')] 
+0

非常感谢:) –

0

对方回答是好的,但它需要对list1list2进行排序并且每个字母的编号相同。

以下程序适用于所有情况:

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) 

输出:

>>> ================================ RESTART ================================ 
>>> 
a - A 2 
b - B 1 
c - C 1 
>>>