Python 如何找到最常见的字符?
我想写一个程序,让用户输入一个字符串,然后显示的字符,出现在他们的输入字符串最频繁。我最初编写了一个程序,计算一个特定字母(字母T)出现的次数,但希望将其转换。不过,这可能需要一个全新的代码 我以前的计划是:Python 如何找到最常见的字符?,python,Python,我想写一个程序,让用户输入一个字符串,然后显示的字符,出现在他们的输入字符串最频繁。我最初编写了一个程序,计算一个特定字母(字母T)出现的次数,但希望将其转换。不过,这可能需要一个全新的代码 我以前的计划是: # This program counts the number of times # the letter T (uppercase or lowercase) # appears in a string. def main(): # Create a variable to
# This program counts the number of times
# the letter T (uppercase or lowercase)
# appears in a string.
def main():
# Create a variable to use to hold the count.
# The variable must start with 0.
count = 0
# Get a string from the user.
my_string = input('Enter a sentence: ')
# Count the Ts.
for ch in my_string:
if ch == 'T' or ch == 't':
count += 1
# Print the result.
print('The letter T appears', count, 'times.')
# Call the main function.
main()
类似于,但我不熟悉那里使用的很多东西。我认为我使用的Python版本比较旧,但我可能不正确。您可以使用Py的std lib中的
集合。Counter
。看一看 还有一个小例子:
>>> from collections import Counter
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
编辑 一艘客轮
count = [(i, string.count(i)) for i in set(string)]
或者,如果您想编写自己的函数(这很有趣!),您可以从以下内容开始:
string = "abracadabra"
def Counter(string):
count = {}
for each in string:
if each in count:
count[each] += 1
else:
count[each] = 1
return count # Or 'return [(k, v) for k, v in count]'
Counter(string)
out: {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}
不过,这不会显示出联系。这将:
>>> s = 'abracadabrarrr'
>>> lcounts = sorted([(i, s.count(i)) for i in set(s)], key=lambda x: x[1])
>>> count = max(lcounts, key=lambda x: x[1])[1]
>>> filter(lambda x: x[1] == count, lcounts)
[('a', 5), ('r', 5)]
另外,
t=t
?我的意思是小写和大写之间有区别吗?'t'!='T'
-小写和大写是完全不同的字母。根据上下文,大写和小写字母可以被视为“相同”。这完全取决于上下文。
>>> s = 'abracadabrarrr'
>>> lcounts = sorted([(i, s.count(i)) for i in set(s)], key=lambda x: x[1])
>>> count = max(lcounts, key=lambda x: x[1])[1]
>>> filter(lambda x: x[1] == count, lcounts)
[('a', 5), ('r', 5)]