2016-04-25 32 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 
>>>