英文:
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 <module>
J=[i for i in J1 not in J2]
TypeError: 'bool' 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]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论