这应该返回代码中出现字母的索引,但它只是要求输入字母和单词。有人可以帮我吗? (我是初学者。)
##task 3
word = input("Enter word: ")
wrdlist = list(word)
wrdlen = len(wrdlist)
l = []
a = 0
char = input("Enter letter: ")
while wrdlen > a:
if char == wrdlist[a]:
l.append(a)
a = a+1
continue
else:
continue
if not l:
print("none")
else:
print(loclist)
答案 0 :(得分:0)
问题:您忘记在a
案例中增加else
。
## task 3
word = input("Enter word: ")
wrdlist = list(word)
wrdlen = len(wrdlist)
l = []
a = 0
char = input("Enter letter: ")
while wrdlen > a:
if char == wrdlist[a]:
l.append(a)
a = a+1
continue
else:
a = a+1
continue
if not l:
print("none")
else:
print(l)
但这是for
循环优先于while
循环的众多原因之一,因为我们可以在这里使用:
## task 3
word = input("Enter word: ")
wrdlist = list(word)
l = []
a = 0
char = input("Enter letter: ")
for a in range(len(word)):
if char == wrdlist[a]:
l.append(a)
if not l:
print("none")
else:
print(l)
此外,我们仍然可以通过使用列表理解来显着改进它:
## task 3
word = input("Enter word: ")
wrdlist = list(word)
l = []
a = 0
char = input("Enter letter: ")
l = [a for a in range(len(word)) if char == word[a]]
if not l:
print("none")
else:
print(l)
我们还可以使用word[a]
enumerate(..)
## task 3
word = input("Enter word: ")
wrdlist = list(word)
l = []
a = 0
char = input("Enter letter: ")
l = [ix for ix, wi in enumerate(word)) if char == wi]
if not l:
print("none")
else:
print(l)
答案 1 :(得分:0)
您的问题源于永不递增您的计数器:a
由于a = a+1
位于if char == wrdlist[a]
,因此只有在条件为真时才会增加循环次数。
您需要做的是:
##task 3
word = input("Enter word: ")
wrdlist = list(word)
wrdlen = len(wrdlist)
l = []
a = 0
char = input("Enter letter: ")
while wrdlen > a:
if char == wrdlist[a]:
l.append(a)
a = a+1
if not l:
print("none")
else:
print(l)
请注意,您不需要else语句,因为无论char
是否与wrdlist[a]
匹配,您都希望计数器增加
答案 2 :(得分:0)
W是索引计数器,l是在索引中找到字母时添加计数器的列表。
word = input("Enter word: ")
char = input('Enter letter: ')
w = 0
l = []
for _ in word:
if _ == char:
l.append(w)
w+=1
print(l)
答案 3 :(得分:0)
您的计划有以下缺点:
正确更新控件变量a
,如下所示
while wrdlen > a:
if char == wrdlist[a]:
l.append(a)
a = a+1
另外,将loclist
替换为l
假设您要打印特定字符出现的索引列表,以下脚本有帮助
word = input("Enter word: ")
char = input("Enter letter: ")
occurrences = [index for index in range(len(word)) if word[index] == char]
print(occurrences if occurrences else "none")