[英]Finding missing element in a list in Python
I have two lists J2
and J10
.我有两个列表
J2
和J10
。 I am trying to find the elements in J10
which are absent in J2
but I am getting an error.我试图在
J10
中找到J2
中不存在的元素,但出现错误。 I present the expected output.我提出了预期的 output。
J2=[128, 4, 6, 7, 8, 9, 10]
J10=[4, 6, 7, 8, 9, 10, 13, 128]
J=[i for i in J10 not in J2]
print(J)
The error is错误是
in <module>
J=[i for i in J10 not in J2]
TypeError: 'bool' object is not iterable
The expected output is预期的 output 是
[13]
J=[i for i in J10 if i not in J2]
Or:要么:
lst=[]
for i in J10:
if i not in J2:
lst.append(i)
#[13]
Or要么
set(J10)-(set(J2))
This will do the job:这将完成工作:
temp = list(filter(lambda x: x not in J2, J10))
print(temp)
Here is why your code fails:这就是您的代码失败的原因:
J10 not in J2
is treated as an expression that checks if J10 (as a whole is in J2). J10 not in J2
被视为检查 J10 是否(作为一个整体在 J2 中)的表达式。 In other words, the J10 not in J2
will be either True or False and since a boolean is not a storage-like element such as a list, you can not iterate it.换句话说,
J10 not in J2
要么为 True,要么为 False,并且由于 boolean 不是类似于列表的存储元素,因此您无法迭代它。 if you want to solve your problem with syntax you were trying, you should use:如果你想用你正在尝试的语法解决你的问题,你应该使用:
J=[i for i in J10 if i not in J2]
J=[i for i in J10 if i not in J2]
print(set(J2).symmetric_difference(J10))
Your code does not work because it's parsed as:您的代码不起作用,因为它被解析为:
[i for i in (J10 not in J2)]
J10 not in J2
returns a boolean value that you can't iterate over. J10 not in J2
返回您无法迭代的 boolean 值。 You are missing an if
.您缺少
if
。
[i for i in J10 if i not in J2]
Sets may be useful here, though, as the membership check if O(len(J2)) and the outer loop is O(len(J10)), making this a potentially quite expensive approach.不过,集合在这里可能很有用,因为成员资格检查是否为 O(len(J2)) 并且外循环是否为 O(len(J10)),这使得这种方法可能非常昂贵。
>>> set(J10) ^ set(J2) & set(J10)
{13}
First we find the set of items that are unique to each set.首先,我们找到每组唯一的项目集。 TO ensure this contains only unique elements from
J10
, we then intersect with J10
.为了确保它仅包含来自
J10
的唯一元素,我们随后与J10
相交。
Try this way..试试这个方法..
J2=[128, 4, 6, 7, 8, 9, 10]
J10=[4, 6, 7, 8, 9, 10, 13, 128]
J=list(set(J10).difference(J2))
print(J)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.