[英]How to use a while loop to count the number of times a specific number appears in a list?
[英]How to count the number of times a specific character appears in a list?
好的,這是一個列表:
sentList = ['I am a dog', 'I am a cat', 'I am a house full of cards']
我希望能夠計算用戶輸入的字母在整個列表中出現的總次數。
userLetter = input('Enter a letter: ')
假設字母是“a”
我希望程序通過 go 並計算“a”出現在列表中的次數。 在這種情況下,列表中“a”的總數應為 8。
我已經嘗試通過 for 循環使用計數 function,但我不斷得到我不知道如何解釋的數字,也不知道如何格式化循環,或者我是否需要它。
我試過這個,但它不起作用。
count = sentList.count(userLetter)
任何幫助將不勝感激,我找不到任何文檔來計算列表中字母的所有出現次數。
將所有字符串合並為單個字符串,然后使用count函數。
count = ''.join(sentList).count(userLetter)
使用內置的sum()
可以將列表中每個字符串的計數加起來:
total = sum(s.count(userLetter) for s in sentList)
您的方法是正確的。 問題是您需要仔細檢查list
。
word_count=0
for l in sentList:
word_count+= l.count(userLetter)
你嘗試過這樣的事情嗎?
userLetter = input('Enter a letter: ')
sentList = ['I am a dog', 'I am a cat', 'I am a house full of cards']
letterCount = 0
for sentence in sentList:
letterCount += sentence.count(userLetter)
print("Letter appears {} times".format(letterCount))
word_list = ["aardvark", "baboon", "camel"] import random chosen_word = random.choice(word_list) guess = input("猜一個字母:").lower()
對於 chosen_word 中的字母:if letter == guess: print("Right") else: print("Wrong")
檢查輸入的字母是否出現在隨機選擇的單詞中的示例程序
word_list = ["aardvark", "baboon", "camel"]
import random
chosen_word = random.choice(word_list)
guess = input("Guess a letter: ").lower()
for letter in chosen_word:
if letter == guess:
print("Right")
else:
print("Wrong")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.