简体   繁体   English

比较列表。 哪些元素不在列表中?

[英]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.

相关问题 创建列表列表。 修改列表中的元素 - Create a list of lists. Modify elements in the list 列表列表中的元素相等。 删除一个 - Equal elements in list of lists. Delete one 比较列表中的元素 - comparing elements in list of lists 在包含多个列表的列表中检索随机对象。 蟒蛇 - Retrieve random object in a list which contains multiple lists. Python 比较两个列表的长度。 他们为什么不同? - Comparing the lengths of two lists. Why are they different? 用于列表列表的空间高效数据存储。 元素是整数,所有列表的大小都不同 - Space efficient data store for list of list of lists. Elements are integers, and size of all lists varies in length 通过比较 Python 中列表元素的值来比较列表 - Comparing lists by comparing values of elements of the list in Python 写一个最长的 function,它也需要一个列表 ll 的列表。 它应该返回(引用) ll 中最长的列表 - Write a function longest, which also takes a list ll of lists. It should return (a reference to) the longest of the lists in ll 我有所有列表。 我想从每个列表中删除几个元素 - I have al list of lists. I want to remove several elements from every list 处理python列表。 (访问特定元素) - Manipulating python lists. (accessing specific elements)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM