我在数一封信在我的单子上出现了多少次。但是,每当我使用count函数并输入要计数的字母时,我的return=0
代码如下:
lab7 = ['Euclid','Archimedes','Newton','Descartes','Fermat','Turing','Euler','Einstein','Boole','Fibonacci', 'Nash']
print(lab7[1]) #display longest name - a
print(lab7[10]) #display shortest name - b
c = [ word[0] for word in lab7]
#display str that consists of 1st letter from each name in list - c
print(c)
d = [ word[-1] for word in lab7]
#display str that consists of last letter from each name in list - d
print(d)
**x = input('Enter letter you would like to count here')
lab7.count('x')
e = lab7.count('x')
print(e)**
这是代码中不起作用的部分。我不断得到->
Archimedes
Nash
['E', 'A', 'N', 'D', 'F', 'T', 'E', 'E', 'B', 'F', 'N']
['d', 's', 'n', 's', 't', 'g', 'r', 'n', 'e', 'i', 'h']
Enter letter you would like to count here s
0
作为我的输出。你知道吗
@ZdaR的解决方案是最好的,如果你只想数一次字母。如果您想在同一个字符串上多次获取字母,那么使用
collection.Counter
会更快。示例:如果要计算
list
中所有单词中给定字符的出现次数,可以尝试:如果希望逻辑不区分大小写,可以使用
.lower()
将输入字符转换为小写首先连接
list
的所有元素以获得统一的字符串,然后使用count
方法获得给定字符的出现次数。你知道吗它将连接列表中包含的所有单词并生成一个字符串。然后字符串将被降低,以便计算大小写字母(例如
A
等于a
)。如果大写字母和小写字母不应该一视同仁,那么.lower()
可以删除。你知道吗要检查输入是否只有一个字母:
相关问题 更多 >
编程相关推荐