所以我有一个存储的单词。并且邀请用户检查他们选择的字母是否在这个单词中。我的代码是以下
storedword = "abcdeef"
word = list(germ)
print (word)
merge = input("letter please")
print ("your letter is", merge)
counter = int(0)
letterchecker = int(0)
listlength = len(word)
while counter < listlength and merge != word[counter]:
counter +=1
if counter <listlength:
print ("found")
else:
print ("not found")
如何更改此代码以检查用户信函在此单词中的次数?我只能使用if和while循环而不使用.count
答案 0 :(得分:1)
len([w for w in word if w == merge])
是
的缩写x = []
for w in word:
if w == merge:
x.append(w)
len(x)
与while循环类似的方法:
i = x = 0
while i < len(word):
if word[i] == merge:
x += 1
i += 1
答案 1 :(得分:1)
您可以使用Counter
from collections import Counter
storedword = "abcdeef"
wordcounter = Counter(list(storedword))
merge = input("letter please ")
print("your letter is %s" % merge)
print('It occurs %d times' % wordcounter[merge])
答案 2 :(得分:0)
counter = 0
letter_count = 0
while counter < len(word);
if word[counter] == merge:
letter_count +=1
counter +=1
答案 3 :(得分:0)
试试这个:
counter = 0
for c in word:
if c == merge:
counter += 1
如果您无法使用,请使用:
counter = 0
ind = 0
while ind < len(word):
if word[ind] == merge:
counter += 1
ind +=1