python - 为什么此列表不起作用...“TypeError:列表索引必须是整数或切片,而不是 str”
问题描述
我是 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)
解决方案
Stephen 和 U9 都给出了很好的解决方案。我将解释为什么您的代码不起作用。请注意,plural_words 是一个字符串列表。因此,当您调用 时for i in plural_words:
,您正在迭代该列表中的单词,因此每次迭代都会获得字符串本身(而不是数字)。例如:
输入:
plural_words = ['bark','dog','cats']
for i in plural_words:
print(i)
输出:
bark
dog
cats
由于每次迭代都将 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)
.
推荐阅读
- java - Eclipse中孟加拉语辅音断音问题的解决方法是什么?
- prometheus - 如何使用标签名称进行普罗米修斯警报表达?
- docker - 高效地在 docker 中创建用户
- aggregate - 使用 LOD 在 Tableau 中计算最大布尔值
- c# - 希望将 T 应用于字典值
- google-analytics - 如何在 GA 中使用 BigQuery 计算流失率
- javascript - 有没有办法避免嵌套的 switch 语句
- ocaml - 为什么 Num 的有理数打印为
? - python - How to detect records that appear on a larger interval than the specified one?
- selenium-webdriver - 如何在 webdriverio 中使用重新运行服务?