程序不返回索引

时间:2018-01-01 00:49:56

标签: python python-3.x list while-loop append

这应该返回代码中出现字母的索引,但它只是要求输入字母和单词。有人可以帮我吗? (我是初学者。)

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

4 个答案:

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

您的计划有以下缺点:

  1. 由于条件和更新变量 a 的错误组合,它可能会进入无限循环。在与输入字符串的任何错误配合中,代码将进入无限循环
  2. loclist 未定义
  3. 正确更新控件变量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")