簡體   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