如何使用python计算字母出现的次数?

如何使用python计算字母出现的次数?,python,frequency,Python,Frequency,我在试着数一数一封信在我的列表中出现了多少次。但是,每当我使用count函数并输入字母时,我希望计数我的返回=0 代码如下: lab7 = ['Euclid','Archimedes','Newton','Descartes','Fermat','Turing','Euler','Einstein','Boole','Fibonacci', 'Nash'] print(lab7[1]) #display longest name - a print(lab7[10]) #disp

我在试着数一数一封信在我的列表中出现了多少次。但是,每当我使用count函数并输入字母时,我希望计数我的返回=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

作为我的输出

如果要在
列表中的所有单词中计算给定字符的出现次数
,则可以尝试:

input_char = input('Enter letter you would like to count here')
print "".join(lab7).count(input_char)
如果希望逻辑不区分大小写,则可以使用
.lower()

首先将
list
的所有元素连接起来以获得统一的字符串,然后使用
count
方法获取给定字符的出现次数

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))

@如果你只想数一次字母,ZdaR的解决方案是最好的。如果要在同一字符串上多次获取字母,则使用
集合.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]

您还可以使用sum+a生成器:

letter = letter.lower()
count = sum(w.lower().count(letter) for w in lab7)

在count调用中,传递的是字母x而不是变量x。您可能打算编写
lab7.count(x)
lab7.count(x)
。为什么要硬编码最短和最长字符串的位置?我非常怀疑这会“通过你的任务”,我不明白为什么会被否决。每次我试图写lab7.count(x)时,我都会收到“无效语法”错误,这只是
x
'x'
@Nulano之间的一个输入错误。我只是用字母x而不是变量来查看其余代码的运行情况。@Marisa我知道,更改后命令不正常,但这是问题的一半。请从x@cricket_007我假设输入是
x
,如OP
lab7所示。count('x')
基于
x=
行,我想不是的,但它有点混淆实际需求是什么,但是我改变了代码,以字符作为输入。你需要降低输入,并可能将其限制为1个字符。快速浏览问题,并假设每个单词的出现次数应单独计算,然后返回。@sphericalcowboy cowboy/谢谢,这很有效!我尝试了所有其他方法来获得正确的字母计数,但结果都是错误的数字。您只需将
.lower()
添加到Zdar的解决方案中,它看起来就像我的解决方案。我添加了更多的信息,希望能够让人们更容易地遵循这些步骤,并添加了代码来检查输入是否正确。