簡體   English   中英

當元素包含在變量中時,如何從Python中的列表中刪除元素

[英]How to remove an element from a list in Python when element is contained in a variable

我是編程新手,剛剛完成UNI的第一學期課程。 在處理課程作業的最后細節時,我遇到了一個挑戰,但尚未找到堆棧溢出的答案。

我有一個名為cL(coloursList)的列表,並且正在嘗試從該列表中刪除一個元素,該元素包含在一個名為“ colour2”的變量中,該變量由用戶使用“ input”方法通過外殼輸入。

我發現通過引用元素本身(通過提供元素名稱作為字符串)或列表中元素的索引位置,使用list.remove(x)或list.pop(x)從列表中刪除元素的方法。

這就是我正在使用的代碼的樣子:

    # more code before this

    cL = ["red", "green", "blue", "magenta", "orange", "pink"]

    elif colour2 == colour1:
        cL = cL.remove(colour2)
        print("\nPlease select a different colour than previous one:\n", cL) 
        colour2 = str(input("Please re-enter second colour: "))

    # more code to follow

基本上,我要在這里實現的是,當用戶輸入第二種或第三種顏色時,會在外殼中提示他,如果他輸入先前從列表中使用過的顏色,則嘗試從中刪除該顏色。列表,然后向用戶顯示新的修改列表,因此他知道自己剩下的顏色可供選擇。

顯然,我嘗試過的這段代碼不起作用

cL = cL.remove(colour2)

並且正在嘗試查看實現此任務的選項。

非常感謝你!

*******更新包含完整代碼(適用於好奇的人)*******

*******在STACK OVERFLOW社區的幫助下完成了任務*******

    cL = ["red", "green", "blue", "magenta", "orange", "pink"]

print("\nAvailable colours to choose from:\n", cL)
colour1 = str(input("Please enter FIRST colour: ")).lower()
while True:
    if colour1 not in cL:
        print("\nInvalid colour.\nPlease choose a colour from list:\n", cL)
        colour1 = str(input("Please re-enter a valid FIRST colour: "))\
                      .lower()
    else:
        cL.remove(colour1)
        break

print("\nGREAT WORK! Remaining valid colours to choose from are:\n", cL)        
colour2 = str(input("Please enter SECOND colour: ")).lower()
while True:
    if colour2 not in cL:
        print("\nInvalid colour.\nPlease choose a colour from list:\n", cL)
        colour2 = str(input("Please re-enter a valid SECOND colour: "))\
                      .lower()
    else:
        cL.remove(colour2)
        break

這就是我完成的顏色輸入驗證代碼的樣子(用於第一和第二種顏色)。 認為這可能會幫助將來完成類似任務的人完成任務。

*顏色輸入可以是[小寫],[大寫]或[混合],除非用戶在選擇任何一種顏色之前選擇呈現給他的一種顏色,否則他將陷入循環詢問中他從提供的列表中選擇有效的顏色。

你快到了

方法list.remove()修改列表,但不返回修改后的列表本身。

因此,如果您執行以下操作:

cL.remove(colour2)
print(cL)

它應該會給您所需的響應。

另一種方法是:

colour2 = str(input("Please re-enter second colour: "))    
cL = [x for x in cL if x != colour2]

由於您不僅限於colour2而且希望多次執行相同的操作,因此我提供了一種更通用的解決方案,該解決方案適用於任意數量的輸入,除非您輸入q

cL = ["red", "green", "blue", "magenta", "orange", "pink"]
deleted = []

while True:
    colour = input("Please enter a colour to delete: (press q to quit)")
    if colour == 'q':
        break
    if colour not in deleted:
        cL.remove(colour)
        deleted.append(colour)
    else:
        print ("%s already deleted. Try entering another color" %colour)

樣本輸出

Please enter a colour to delete: (press q to quit)red
Please enter a colour to delete: (press q to quit)red
red already deleted. Try entering another color
Please enter a colour to delete: (press q to quit)green
Please enter a colour to delete: (press q to quit)pink
Please enter a colour to delete: (press q to quit)red
red already deleted. Try entering another color
Please enter a colour to delete: (press q to quit)green
green already deleted. Try entering another color
Please enter a colour to delete: (press q to quit)q

因此,據我了解,您有一個顏色列表,並且希望用戶開始從該列表中選擇顏色,並且如果他選擇了不在列表中的顏色或已經選擇的顏色,則應該告訴他選擇其他顏色。

如果是這種情況,它將是什么樣子

colors_list = ["red", "green", "blue", "magenta", "orange", "pink"]
colors_chosen = []

while colors_list:
    print("Please select a color from this list: {}".format(colors_list))
    color_selected = input()

    while color_selected not in colors_list:
        print("The color selected is not one of the options")
        print("Please select a color from this list: {}".format(colors_list))
        color_selected = input()

    colors_list.remove(color_selected)
    colors_chosen.append(color_selected)

print("These are the colors you chose: {}".format(colors_chosen))

因此,我們正在做的是擁有所有可能顏色的列表,並且使用的循環將在此列表不為空的情況下重復進行(如果您只想將while循環替換為for循環,用戶選擇n種顏色而不是所有顏色)。 在該循環內,我們將詢問用戶顏色,如果不是列表內的顏色,它將進入while循環,直到用戶選擇列表內的有效顏色。 一旦用戶選擇了有效的顏色,我們將從列表中刪除該顏色,並將其添加到列表中,以存儲用戶選擇的顏色。 重復此過程,直到顏色列表為空。

如果用戶鍵入的不是顏色(例如“汽車”之類的東西),或者鍵入的是他/她之前已經選擇的顏色,則可能要顯示不同的消息。 為此,您需要檢查用戶鍵入的單詞是否不在顏色列表中,而是在所選單詞列表中,然后打印“您不能選擇已經選擇的單詞!”,如果它不在兩個列表中,則打印“您必須選擇一種實際的顏色!”。

希望能幫助到你!

暫無
暫無

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

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