Python在2个列表中查找组合的频率

时间:2016-04-25 03:14:04

标签: python-3.x

我有2个清单,

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

如何找到'a''A''b''B''c''C'的每种组合的频率?

2 个答案:

答案 0 :(得分: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')]

答案 1 :(得分: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
>>>