我写了下面的代码,我需要从它给出的列表中获取MAX个字符数。
def ssin(a):
ASAS = map(lambda y: (chr(ord('A')+y),len(filter(lambda x: ord(x) - ord('A') == y, a))),range(0,26))
return ASAS
ssin('THE AGES OF THE KINGS')
回答:
[('A', 1), ('B', 0), ('C', 0), ('D', 0), ('E', 3), ('F', 1), ('G', 2),
('H', 2), ('I', 1), ('J', 0), ('K', 1), ('L', 0), ('M', 0), ('N', 1),
('O', 1), ('P', 0), ('Q', 0), ('R', 0), ('S', 2), ('T', 2), ('U', 0),
('V', 0), ('W', 0), ('X', 0), ('Y', 0), ('Z', 0)]
如何找到给定字符串中的MAX个字符数?
答案 0 :(得分:2)
Counter
是你的朋友:
>>> from collections import Counter
>>> Counter(char.upper() for char in 'THE AGES OF THE KINGS' if char.isalpha()).most_common(1)
[('E', 3)]
答案 1 :(得分:0)
您的功能很痛苦,但如果您可以使用它来找到最常见的值:
sorted(ssin('THE AGES OF THE KINGS'), key = itemgetter(1), reverse = True)[0]
没有做任何事情来检查是否存在最频繁的关系。
答案 2 :(得分:0)
>>> import operator
>>> freqinfo = ssin('THE AGES OF THE KINGS')
>>> max(freqinfo,key=operator.itemgetter(1))
('E',3)
基本上max(freqinfo,key=operator.itemgetter(1))
说“查找freqinfo
中freqinfo [i] [1]最大的对象”。因为freqinfo[i]
是(letter,frequency)
对。