猿问

“合并”两个嵌套数组

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

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]]

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


杨魅力
浏览 159回答 2
2回答

幕布斯6054654

正如注释中@Sajan建议的那样,您必须更改语法。如果要循环访问列表的内容:.appendfor things in ingredients:    recipe.append(things)如果要循环访问列表的索引:for index in range(len(ingredients)):    recipe.append(ingredients[index])结果将是相同的。

富国沪深

实际上,您正在尝试传递一个数组作为成分数组的索引。这将不起作用并导致异常TypeError:列表索引必须是整数或切片而不是列表,告诉您不能使用数组对数组进行切片。(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])
随时随地看视频慕课网APP

相关分类

Python
我要回答