在Python中在一个列表中查找另一个列表的元素。

huangapple go评论69阅读模式
英文:

Finding elements of one list in another in Python

问题

import numpy as np
J1 = [1, 2, 4, 6, 7, 9, 10]
J2 = [0, 2, 0, 6, 7, 9, 10]

J = [i for i in J1 if i not in J2]
print(J)

错误信息是:

in <module>
    J = [i for i in J1 if i not in J2]
TypeError: 'bool' object is not iterable

期望的输出是:

J = [1, 4]
英文:

I have two lists J1,J2. I want to find elements of J1 which are not in J2. But I am getting an error. I present the expected output.

import numpy as np
J1=[[1, 2, 4, 6, 7, 9, 10]]
J2=[[0, 2, 0, 6, 7, 9, 10]]

J=[i for i in J1 not in J2]
print(J)

The error is

in &lt;module&gt;
    J=[i for i in J1 not in J2]

TypeError: &#39;bool&#39; object is not iterable

The expected output is

J=[[1,4]]

答案1

得分: 1

输出:

[[1, 4], [0, 2]]
英文:

Taking J1 and J2 as list of lists for better understanding.

Code:

import numpy as np

J1 = [[1, 2, 4, 6, 7, 9, 10], [0, 2, 3, 1]]
J2 = [[0, 2, 0, 6, 7, 9, 10], [1, 3, 5]]

J = [[x for x in J1[i] if x not in J2[i]] for i in range(len(J1))]

print(J)

Output:

[[1, 4], [0, 2]]

huangapple
  • 本文由 发表于 2023年3月9日 19:06:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683747.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定