我正在计算一封信出现在我的列表中的次数。但是,每当我使用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
作为我的输出。
答案 0 :(得分:4)
如果你想计算list
中所有单词中给定角色的出现次数,那么你可以试试:
input_char = input('Enter letter you would like to count here')
print "".join(lab7).count(input_char)
如果您希望逻辑是大小写的,您可以使用.lower()
将输入字符转换为小写
首先连接list
的所有元素以获取统一字符串,然后使用count
方法获取给定字符的出现。
答案 1 :(得分:1)
lst = ['Euclid', 'Archimedes', 'Newton', 'Descartes', 'Fermat',
'Turing', 'Euler', 'Einstein', 'Boole', 'Fibonacci', 'Nash']
letter = input("Enter the letter you would like to count: ")
count = "".join(lst).lower().count(letter)
print(count)
将加入列表中包含的所有单词并生成单个字符串。然后降低字符串以计算大写和小写字母(例如A
等于a
)。如果不应平等对待大写和小写字母,则可以删除.lower()
。
检查输入是否只是一个字母:
lst = ['Euclid', 'Archimedes', 'Newton', 'Descartes', 'Fermat',
'Turing', 'Euler', 'Einstein', 'Boole', 'Fibonacci', 'Nash']
letter = input("Enter the letter you would like to count: ")
while not letter.isalpha() or len(letter) != 1:
letter = input("Not a single letter. Try again: ")
print("".join(lst).lower().count(letter))
答案 2 :(得分:1)
@ ZdaR的解决方案如果你想只计算一次字母,最好。如果您想在同一个字符串上多次获取字母,则使用collection.Counter
会更快。例如:
from collections import Counter
counter = Counter("".join(lab7))
while True:
input_char = input('Enter letter you would like to count here')
print counter[input_char]
答案 3 :(得分:0)
您也可以使用sum + a generator:
letter = letter.lower()
count = sum(w.lower().count(letter) for w in lab7)