簡體   English   中英

嘗試使用 While 循環創建列表列表,並附加一個使用輸入清除和更新的列表。 不工作。 怎么修?

[英]Trying to create a list of lists by using a While Loop and appending a list that clears and updates with inputs. Doesn't work. How to fix?

如果我的措辭是基本的,請提前抱歉,我是一名大學生,這樣做是為了好玩。

我正在嘗試使用while循環通過附加一個“更新列表”來創建一個列表列表(LoL),該“更新列表”會清除、更新然后再次附加到列表列表中。

但是,這將更新 LoL 並創建一個由(更新列表 * 我附加了多少次)組成的列表。

這就是我的意思:

fulllst = [] # List of Lists
temp = [] # Updating List


while True:
    temp.clear() 
    while True:
        item = input("Enter item: ")
        if item == "done": #Ends the updating list and sends it back to be cleared.
            fulllst.append(temp)
            print(fulllst)
            break
        else:
            temp.append(item)
            print(fulllst)
            continue

所以我的問題是:圍繞這個我能對 go 做些什么? 我需要它,以便我可以 append 多次使用不同的值多次列出相同的列表。

謝謝。

編輯:例如,我想制作 1 個列表,其中包含 3 個內部具有不同值的列表。 它不適用於此代碼,因為因為我附加了“更新列表”,所以每當我在循環開始時清除它時,它都會清除 LoL 中的列表。 我試圖在這張圖片中展示這一點:

嘗試制作三個不同列表的圖像。

將 temp 移至內部 while 循環:

fulllst = [] # List of Lists

while True:
    temp = [] # Updating List
    while True:
        item = input("Enter item: ")
        if item == "done": #Ends the updating list and sends it back to be cleared.
            fulllst.append(temp)
            print(fulllst)
            break
        else:
            temp.append(item)
            print(fulllst)
            continue

代碼中要修復的區域:

  1. temp = [] 需要在主 while 循環內。
  2. 您沒有退出主 while 循環。 您的 break 語句僅從內部 while 循環中退出

請參閱我的更改以解決這些問題:

如果您想要多個列表列表,則需要將 go 重新放入循環中。 在這種情況下,您根本沒有退出主循環。

fulllst = [] # List of Lists
ans = 'y'
while ans.lower().startswith('y'):
    temp = [] # Updating List
    while True:
        item = input("Enter item: ")
        if item == "done": #Ends the updating list and sends it back to be cleared.
            fulllst.append(temp)
            break
        else:
            temp.append(item)
    ans = input ('do you want another list of list item [Y/N] : ')
print (fulllst)

下面將為您提供以下答案:

Enter item: apple
Enter item: banana
Enter item: done
do you want another list of list item [Y/N] : y
Enter item: cake
Enter item: sugar
Enter item: done
do you want another list of list item [Y/N] : n
[['apple', 'banana'], ['cake', 'sugar']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM