我有一个像这样的 python 列表:
List = [s,b,s,d,h,a,h,e,h,a]
有没有一种简单的方法可以找出最频繁出现的字母。
在我的列表中:
h,a = 2x
如果能有一个完整的表格,说明哪些字母跟在哪些频率后面,那将是非常酷的。但我不确定如何解决这个问题
b d a e
s 1 1
h 2 1
请您参考如下方法:
您可以使用zip 和collections.Counter获得具有这些频率的后续对:
>>> from collections import Counter
>>> c= Counter(zip(l,l[1:]))
Counter({('h', 'a'): 2, ('d', 'h'): 1, ('s', 'b'): 1, ('s', 'd'): 1, ('b', 's'): 1, ('h', 'e'): 1, ('a', 'h'): 1, ('e', 'h'): 1})
然后用most_common方法你可以得到最常见的对:
>>> c.most_common(1)
[(('h', 'a'), 2)]
