简体   繁体   English

尽管使用 for 循环添加元素,为什么我的列表仍然为空

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

I'm trying to do the following: - check if the element from one list exists in another list.我正在尝试执行以下操作: - 检查一个列表中的元素是否存在于另一个列表中。 If so, do nothing, if not append it to that list.如果是这样,什么都不做,如果不是,则将其附加到该列表中。

Simplefied example code:简化示例代码:

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

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

Unfortunately it does not work and as a beginner I'm not sure why.不幸的是它不起作用,作为初学者我不知道为什么。 Any thoughts?有什么想法吗?

The reason why your code doesn't work, is that the statement:您的代码不起作用的原因是该语句:

if item in y=='False':

checks if the boolean answer of the condition检查条件的布尔答案是否

item in y

is equal to the string 'False' for it to trigger the if block.等于字符串'False'以触​​发if块。


Based on your question, the code correction should be:根据您的问题,代码更正应该是:

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

In the above example, the if block is entered when there is an item in x that is not present in list y在上面的例子中,当列表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)

Gives:给出:

[2, 3, 4, 1]

You should use:你应该使用:

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

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

The line: if item in y=='False': will never be true because if an item is not in y, it will return the boolean False, not the string 'False'行: if item in y=='False':永远不会为真,因为如果项目不在 y 中,它将返回布尔值 False,而不是字符串 'False'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM