繁体   English   中英

使用循环在 python 中插入列表

[英]Inserting a list in python using a loop

我正在尝试制作一个可以插入食谱的 python 程序,并且我想列出成分。 我知道如何使用.insert 将数据插入到列表中的某个位置,但是当我使用 for 循环时,我不断收到错误消息“TypeError: insert expected 2 arguments, got 1.” 我不知道我做错了什么。 请帮忙。

print("")
ingred=[]
measure=[]
n=0
i=0
for n in range(0,n+1):
    ingred[n]=ingred.insert(input("What is the ingredient?(type done to end ingrediants)"))
    n=n+1
    measure[i]=measure.insert(input("How much of the ingredient?"))
    i=i+1

使用 append function:

print("")
ingred=[]
measure=[]
n=10
for n in range(0,n+1):
    ingred.append(input("What is the ingredient?(type done to end ingrediants)"))
    measure.append(input("How much of the ingredient?"))

我不太了解你的n=n+1代码,所以我在这里删除了它 - 这应该只运行 N 次,我设置为 10。

insert() function 需要两个 arguments,要插入的元素和要插入的索引。 要在列表末尾插入配方,请使用append()

您不会通过分配给索引来添加到列表中。 您使用append()方法。

如果您想在他们输入end时停止,您需要将输入分配给一个变量,以便您可以在添加到列表之前对其进行检查。

while True:
    name = input("What is the ingredient?(type done to end ingrediants)")
    if name == 'done':
        break
    ingred.append(name)
    measure.append(input("How much of the ingredient?"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM