简体   繁体   English

如何使用python获取两个单独列表中存在的值

[英]how to get value exists in two separate lists using python

Compare two lists and find duplicate that exist in both lists from two lists remove the existing duplicates and create new lists.比较两个列表并从两个列表中找到两个列表中存在的重复项删除现有重复项并创建新列表。

Input 
a=  [
"DJI_0229.jpg",
"DJI_0232.jpg",
"DJI_0233.jpg"
"DJI_0235.jpg"
]
b= [
"DJI_0229.jpg",
"DJI_0232.jpg",
"DJI_0233.jpg"
"DJI_0230.jpg",
"DJI_0231.jpg",
"DJI_0234.jpg"
]

output = 
[
"DJI_0230.jpg",
"DJI_0231.jpg",
"DJI_0234.jpg",
"DJI_0235.jpg"
]

you can use this你可以用这个

def remove_dupilicate(List1,List2):
    return [item for item in List1 if item not in List2]

new_a = remove_dupilicate(a, b)
new_b = remove_dupilicate(b, a)
print(new_a,new_b)

output for new_a list is ['DJI_0235.jpg'] and new_b list is ['DJI_0230.jpg', 'DJI_0231.jpg', 'DJI_0234.jpg'] new_a 列表的输出是['DJI_0235.jpg']和 new_b 列表是['DJI_0230.jpg', 'DJI_0231.jpg', 'DJI_0234.jpg']

you can do this你可以这样做

a= ["DJI_0229.jpg","DJI_0232.jpg","DJI_0233.jpg","DJI_0235.jpg"]
b= ["DJI_0229.jpg","DJI_0232.jpg","DJI_0233.jpg","DJI_0230.jpg","DJI_0231.jpg","DJI_0234.jpg"]
c = []
for image in (a+b):
    if image not in c:
        c.append(image)
    else:
        c.remove(image)
print(c)

The most simplest way to achieve what you want is using symmetric difference of sets.实现您想要的最简单的方法是使用集合的对称差异。 Consider the below venn diagram :考虑下面的维恩图:

2组对称差的维恩图

Code implementation代码实现

from pprint import pprint

a = ["DJI_0229.jpg", "DJI_0232.jpg", "DJI_0233.jpg", "DJI_0235.jpg"]

b = [
    "DJI_0229.jpg",
    "DJI_0232.jpg",
    "DJI_0233.jpg",
    "DJI_0230.jpg",
    "DJI_0231.jpg",
    "DJI_0234.jpg",
]

final_list = sorted(
    list(
        set(a).symmetric_difference(set(b))  # Using some maths :-)
    )  # Converting the set to list
)  # Sorting the resultant list

pprint(final_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何知道一个值是否存在于三个单独的列表中? - How to know if a value exists in three separate lists? 如何将python列表上的每月和每天的文件名分成两个单独的列表? - How to separate monthly and daily filenames on python list into two separate lists? 如何检查 python 的列表列表中是否存在值? - How to check if a value exists in a list of lists of lists in python? 使用python以正确对齐方式在两个单独的列表中打印项目 - Printing items in two separate lists in proper alignment using python 如何将一个列表分为两个不同的列表?(Python2.7) - How to separate a list into two different lists ?(Python2.7) 根据元素的某些方面,如何将Python列表分成两个列表 - How to separate a Python list into two lists, according to some aspect of the elements Python-如何将列表动态拆分为两个单独的列表 - Python - How to split a list into two separate lists dynamically 我如何将这些数据分成两个单独的列表,分别为 python 中的 plot? - How would I split these data in to two separate lists to plot in python? 如何使用python在文本文件中获取每个键一个单独的值 - How to get each key an value separate in text file using python 如何使用 isinstance() 根据对象的类型将列表分成两个列表? - How to separate a list into two lists according to the objects' types using isinstance()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM