2017-03-05 40 views
3

我正在計算一個字母出現在列表中的次數。但是,每當我使用計數功能和輸入我想我算回報信= 0如何計算使用python顯示一個字母的次數?

這是代碼:

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

在計數通話,要傳遞的字母x代替變量x。您可能應該寫'lab7.count(x)'和'lab7.count(x)'來代替。 – Nulano

+1

爲什麼你難以編碼最短和最長的字符串的位置?我高度懷疑這將「通過你的任務」 –

+0

我不明白爲什麼它是upvoted。這是'x'和''x'之間的拼寫錯誤 –

回答

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

您需要降低輸入,並可能將其限制爲1個字符。 –

+0

您可以刪除生成器的列表理解。 'sum(word.lower()....)' –

+0

太快瀏覽問題,並假設每個單詞的出現次數應單獨計算並在之後返回。 –

4

如果你想躋身list所有單詞數給定的人物的出現次數,那麼你可以嘗試:

input_char = input('Enter letter you would like to count here') 
print "".join(lab7).count(input_char) 

如果你想成爲區分insensetive的邏輯中,你可以轉換輸入字符使用.lower()

你先串聯的list所有元素得到一個統一的字符串,然後使用count方法來獲取給定的人物的出現次數小寫。

+0

從x –

+0

@ cricket_007我假定輸入視爲'x'如圖OP'lab7.count(「X」)刪除引號基於' – ZdaR

+0

的'X ='線,我猜不是 –

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

您還可以使用總和+發電機:

letter = letter.lower() 
count = sum(w.lower().count(letter) for w in lab7) 
相關問題