簡體   English   中英

盡管使用 for 循環添加元素,為什么我的列表仍然為空

[英]Why does my list stay empty despite adding elements using a for loop

我正在嘗試執行以下操作: - 檢查一個列表中的元素是否存在於另一個列表中。 如果是這樣,什么都不做,如果不是,則將其附加到該列表中。

簡化示例代碼:

x=[1,2,3]
y=[2,3,4]

for item in x:
    if item in y=='False':
        y.append(item)
    else:
        continue
print(y)

不幸的是它不起作用,作為初學者我不知道為什么。 有什么想法嗎?

您的代碼不起作用的原因是該語句:

if item in y=='False':

檢查條件的布爾答案是否

item in y

等於字符串'False'以觸​​發if塊。


根據您的問題,代碼更正應該是:

if item not in y:
    y.append(item)

在上面的例子中,當列表y存在x中的項目時,進入if

x=[1,2,3]
y=[2,3,4]

for item in x:
    if item not in y:
        y.append(item)
    else:
        continue
print(y)

給出:

[2, 3, 4, 1]

你應該使用:

x=[1,2,3]
y=[2,3,4]

for item in x:
    if item not in y:
        y.append(item)
    else:
        continue
print(y)

行: if item in y=='False':永遠不會為真,因為如果項目不在 y 中,它將返回布爾值 False,而不是字符串 'False'

暫無
暫無

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

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