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

2024-06-13 15:08:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我在数一封信在我的单子上出现了多少次。但是,每当我使用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

作为我的输出。你知道吗


Tags: 代码nameinforthatcountdisplayword
3条回答

@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]

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

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

相关问题 更多 >