[英]Comparing lists. Which elements are NOT in a list?
I have the following 2 lists, and I want to obtain the elements of list2 that are not in list1:我有以下2个列表,我想获取list2中不在list1中的元素:
list1 = ["0100","0300","0500"]
list2 = ["0100","0200","0300","0400","0500"]
My output should be:我的 output 应该是:
list3 = ["0200","0400"]
I was checking for a way to subtract one from the other, but so far I can't be able to get the list 3 as I want我正在检查一种从另一个中减去一个的方法,但到目前为止我无法获得我想要的列表 3
list3 = [x for x in list2 if x not in list1]
Or, if you don't care about order, you can convert the lists to sets:或者,如果您不关心顺序,可以将列表转换为集合:
set(list2) - set(list1)
Then, you can also convert this back to a list:然后,您还可以将其转换回列表:
list3 = list(set(list2) - set(list1))
could this solution work for you?这个解决方案对你有用吗?
list3 = []
for i in range(len(list2)):
if list2[i] not in list1:
list3.append(list2[i])
list1 = ["0100","0300","0500"]
list2 = ["0100","0200","0300","0400","0500"]
list3 = list(filter(lambda e: e not in list1,list2))
print(list3)
I believe this has been answered here:我相信这已经在这里得到了回答:
Python find elements in one list that are not in the other Python 在一个列表中查找不在另一个列表中的元素
import numpy as np
list1 = ["0100","0300","0500"]
list2 = ["0100","0200","0300","0400","0500"]
list3 = np.setdiff1d(list2,list1)
print(list3)
set
functions will help you to solve your problem in few lines of code... set
函数将帮助您在几行代码中解决您的问题...
set1=set(["0100","0300","0500"])
set2=set(["0100","0200","0300","0400","0500"])
set3=set2-set1
print(list(set3))
set
gives you faster implementation in Python than the Lists............... set
在 Python 中比列表提供更快的实现......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.