简体   繁体   English

使用循环在 python 中插入列表

[英]Inserting a list in python using a loop

I'm trying to make a python program that I can insert a recipe, and I want to make a list of the ingredients.我正在尝试制作一个可以插入食谱的 python 程序,并且我想列出成分。 I know how to insert data as a certain spot in the list, using.insert, but when I use a for loop, I keep getting an error that says "TypeError: insert expected 2 arguments, got 1."我知道如何使用.insert 将数据插入到列表中的某个位置,但是当我使用 for 循环时,我不断收到错误消息“TypeError: insert expected 2 arguments, got 1.” I don't know what I'm doing wrong.我不知道我做错了什么。 Please help.请帮忙。

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

Use the append function:使用 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?"))

I don't really understand your n=n+1 code, so I removed it here - this should just run N times, which I set to be 10.我不太了解你的n=n+1代码,所以我在这里删除了它 - 这应该只运行 N 次,我设置为 10。

The insert() function takes two arguments, the element to insert and the index to insert it. insert() function 需要两个 arguments,要插入的元素和要插入的索引。 To insert a recipe at the end of a list, use append() .要在列表末尾插入配方,请使用append()

You don't add to a list by assigning to an index.您不会通过分配给索引来添加到列表中。 You use the append() method.您使用append()方法。

And if you want to stop when they enter end , you need to assign the input to a variable so you can check it before appending to the list.如果您想在他们输入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