为什么这个列表不起作用…“TypeError:列表索引必须是整数或切片,而不是str“

2024-05-29 02:45:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,正在做一个介绍项目。有人能告诉我为什么这不管用/怎么修理它吗。基本上,用户给出一个单词列表,如果这个单词不是复数,它应该加上一个“s”。但这不管用。。。这是密码。我感谢所有的反馈。非常感谢你。在

def pluralize_words():

#########################################################
#Checks if words in plural_words are indeed plural and corrects them if not##
#########################################################

    global singular_words
    global plural_words

    for i in plural_words:
        if plural_words[i].endswith("s"):
            word_is_plural = True
        else:
            word_is_plural = False
            plural_words[i] = word + "s"

    print(plural_words)

Tags: 项目用户in密码列表ifisdef
3条回答

Stephen和U9都给出了很好的解决方案。我会解释为什么你的代码不起作用。注意,复数单词是一个字符串列表。因此,当您调用for i in plural_words:时,您正在迭代该列表中的单词,因此每次迭代都会得到字符串本身(而不是数字)。例如:

输入:

plural_words = ['bark','dog','cats']
for i in plural_words:
    print(i)

输出:

^{pr2}$

由于每次迭代都将i设置为列表中的字符串,因此使用该字符串作为索引调用列表项是没有意义的(因为列表只能具有整数索引)。如果我使用我的示例复数单词列表运行上面的代码,我将调用的第一个迭代是复数单词['bark'],这将给出您刚刚收到的特定错误。为了避免这个问题,您可以使用U9中提到的enumerate,或者您可以迭代列表长度的范围(因此我将是一个数字)。下面是一个例子:

输入:

plural_words = ['bark','dog','cats']
for i in range(len(plural_words)):
    print('i:', i)
    print('word:', plural_words[i])

输出:

i: 0
word: bark
i: 1
word: dog
i: 2
word: cats

在本例中,len(plural_words)是3,所以您实际上正在运行for i in range(3)。在

需要enumerate

def pluralize_words():
    global singular_words
    global plural_words

    for idx,i in enumerate(plural_words):
        if i.endswith("s"):
            word_is_plural = True
        else:
            word_is_plural = False
            plural_words[idx] = i + "s"

    print(plural_words)    

更好的是:

^{pr2}$

或者:

plural_words=list(map(lambda x: x+'s' if x[-1]!='s' else x,plural_words))

这是列表理解的好地方,我们可以使用endswith('s')来进行评估

words = ['sings', 'dance', 'runs', 'hides']

plural = [i if i.endswith('s') else i + 's' for i in words]
chrx@chrx:~/python/stackoverflow/9.22$ python3.7 uk.py
['sings', 'dances', 'runs', 'hides']

相关问题 更多 >

    热门问题