关于这个项目我真的不知道该怎么办。以下是我试图做的:
# Purpose: This function takes an alphabetic string and prints out the number
# of times each letter(upper-or lower-case) is in the string
# Parameter: string - a string of only alphabetic characters
# Return: None
def letter_counter(string):
counter = 0
string = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
letter = [ ] # ?
while counter <= len(string):
for letter in string:
if i == string[counter]:
counter += 1
return counter
print("The letter", letter, "is in", string, count, "time(s)")
# Do I use append here? For loops? etc.?
输出应该是这样的:
count("bAseBalls")
Letter b is in bAseBalls 2 time(s)
Letter a is in bAseBalls 2 time(s)
Letter s is in bAseBalls 2 time(s)
Letter e is in bAseBalls 1 time(s)
Letter l is in bAseBalls 2 time(s)
我是不是用了很多if语句来打印每个字母在字符串中出现的次数?在这个程序中,你会推荐while和for循环吗?任何帮助都将不胜感激。提前谢谢!你知道吗
你想得太多了。您只需将字符串拆分为小写字母,然后使用
collections.Counter
计算每个字母在列表中出现的次数。你知道吗你不必重新发明轮子来计算字符串中的字符。python可以像遍历列表一样遍历字符串。更好的是:python有自己的ascii字母:
string.ascii_lowercase
在这里,dict理解还可以帮助您保持代码的简单性和python性:
输出:
相关问题 更多 >
编程相关推荐