0

简而言之,我正在制作一个程序,用户可以在其中添加食谱,但我遇到了以下代码的问题:

TypeError: list indices must be integers or slices not list
for things in ingredients:
   recipe.append(ingredients[things])

在这种情况下,配方看起来像这样:

recipe = [["name", "cake"], ["amount", 2]]

成分将是

[["eggs", 12], ["flour", 500]]

我想要做的只是将每个嵌套数组从“成分”添加到“食谱”,这只是我能想到的最简单的事情——我知道如何用字典或 while 循环以不同的方式做到这一点,但是我只是想知道为什么这会导致错误。

4

2 回答 2

0

实际上,您正在尝试将数组作为成分数组的索引传递。

这将不起作用并导致异常 TypeError: list indices must be integers or slices not list,告诉您不能使用数组对数组进行切片。(https://docs.python.org/2.3/whatsnew/section-slices.html

for things in ingredients:
   # things == ["eggs", 12] in the first iteration of the loop
   # and ["flour", 500] in the second, so you can't use ["eggs", 12] or ["flour", 500] as an array index.
   recipe.append(things)

因此,如果您想使用索引,则需要在成分数组长度的范围上循环。

for i in range(len(ingredients)):
   recipe.append(ingredients[i])
于 2020-03-24T15:25:21.180 回答
0

正如@Sajan 在评论中建议的那样,您必须更改.append语法。
如果要遍历列表的内容:

for things in ingredients:
   recipe.append(things)

如果要遍历列表的索引:

for index in range(len(ingredients)):
   recipe.append(ingredients[index])

结果将是相同的。

于 2020-03-24T15:22:29.053 回答