我创建了一个程序来计算每个字母的名称列表。该号码然后存储在单独的列表中。我不尝试打印具有原始列表中使用的最大时间的字母。
我尝试使用.index(max)函数,但这会返回位置值。在这种情况下[4]。字母为“ E”,但我不知道该如何实现。
names = ["Euclid", "Archimedes", "Newton", "Descartes", "Fermat",
"Turing", "Euler", "Einstein", "Boole", "Fibonacci",
"Nash", "Wiles", "Cantor", "Gauss", "Plato"]
alphaCount = [0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0]
print(' ord values for characters ')
print('1 ',ord('A')-ord('A')) # 0
print('2 ',ord('B')-ord('A')) # 1
print('3 ',ord('C')-ord('A')) # 2
# .....
print('26 ',ord('Z')-ord('A'))
for name in names:
for ch in name:
x = ord(ch.upper()) - ord('A')
alphaCount[x] = alphaCount[x] + 1
print('alphaCount == ', alphaCount)
max = max(alphaCount)
most_common = alphaCount.index(max)
print("The most common letter is index value:", most_common)
我返回的是索引值,但是我需要与之相关的字母。
答案 0 :(得分:0)
我建议使用dict
而不是list
存储计数-这样,您就可以在字母和计数之间建立更直接的关系,而不必弄乱偏移量ascii值。 / p>
alpha_count = {'a': 0, 'b': 0, 'c': 0, ...}
alpha_count['b'] += 1
...
或者更好的是,您可以使用Counter为您初始化计数。尝试以下解决方案:
from collections import Counter
names = [...]
alpha_count = Counter()
for name in names:
for ch in name:
alpha_count[ch.upper()] += 1
max_letter, max_count = alpha_count.most_common(1)[0]
print(f"most common letter, '{max_letter}', occurred {max_count} times")