我目前正在尝试使用列表做一个信访柜台。该函数的目标是计算每个字符串中有多少个字符,然后打印出多少个字符串的长度为4。我遇到了一些麻烦,希望能有所帮助。我对python很陌生,所以如果答案很简单,或者错过了冒号或其他内容,我深表歉意。
def count_4let(letter_list):
if letter_list == len(4):
counter+=1
print("The number of words with the length of 4 is", counter)
letter_list = ["Whos","the","leader","of","the","club","thats","made","for","you","and","me","M I C K E Y","M O U S E"]
#main
print(count_4let(letter_list))
答案 0 :(得分:0)
您需要遍历列表的元素。您在每个元素上调用len()
,而不是len(4)
。
在添加变量之前,还需要初始化counter
变量。
该函数应仅返回计数,而不输出任何内容。打印由调用方完成。
def count_4let(word_list):
counter = 0
for word in word_list:
if len(word) == 4:
counter += 1
return counter
letter_list = ["Whos","the","leader","of","the","club","thats","made","for","you","and","me","M I C K E Y","M O U S E"]
#main
print("The number of words with length 4 is", count_4let(letter_list))
答案 1 :(得分:0)
您可以将sum
函数与生成器表达式一起使用,该表达式可输出列表中给定单词的长度是否为4:
def count_4let(letter_list):
return sum(len(word) == 4 for word in letter_list)
答案 2 :(得分:0)
使用map()
和count()
的另一种解决方案
>>> l = ["whos", "the", "leader", "of", "the", "club", "thats", "made", "for", "you", "and", "me", "M I C K E Y", "M O U S E"]
>>> list(map(len, l)).count(4)
3
答案 3 :(得分:0)
首先,您不应该写数字的长度,请考虑一下这是没有意义的:
def count_4let(letter_list):
if len(letter_list) == 4:
counter += 1
print("The number of words with the length of 4 is", counter)
letter_list ["Whos", "the", "leader", "of", "the", "club", "thats", "made", "for", "you"," and", "me", "M I C K E Y", "M O U S E"]
print(count_4let(letter_list))