简体   繁体   English

Python:列表理解,将 2 个列表合并为 1 个具有唯一值的列表

[英]Python: List comprehension, combining 2 lists into 1 with unique values

I want to create a list that contains only elements from the original list a that are not in list b.我想创建一个列表,其中仅包含原始列表 a 中不在列表 b 中的元素。

I have tried using list comprehension, but don't understand why the numbers in the new list are repeated three times.我尝试过使用列表理解,但不明白为什么新列表中的数字重复了三遍。

a = [3, 6, 7, 9, 11, 14, 15]

b = [2, 6, 7, 10, 12, 15]

c = [x for x in a if x not in b 
       for y in b if y not in a]

I expected this result:我期待这个结果:

[3, 9, 11, 14]

An easier way would be to use sets.更简单的方法是使用集合。

set_a = set(a)
set_b = set(b)

c = list(set_a - set_b) #Using set operator difference
c.sort() #If you need to have it in order

Set Operator Difference 设置运算符差异

Solution解决方案

You added too much code您添加了太多代码

a = [3, 6, 7, 9, 11, 14, 15]
b = [2, 6, 7, 10, 12, 15]

c = [x for x in a if x not in b]

This gives the following result just as you wanted!!这就像你想要的那样给出以下结果!

print(c)

# [3, 9, 11, 14]

Why Repeated 3 times?为什么重复3次?

Well look at the orginal data again好吧再看看原始数据

original = [3, 6, 7, 9, 11, 14, 15]
# Index     0  1  2  3   4   5   6
#           ✓  x  x  ✓   ✓   ✓   x  

second = [2, 6, 7, 10, 12, 15]
#         0  1  2   3   4   5
#         ✓  x  x   ✓   ✓   x

You get 4 unique numbers [3, 9, 11, 14] because there are 4 numbers in original that are not in the second list.您得到 4 个唯一数字 [3, 9, 11, 14],因为original数字中有 4 个数字不在second列表中。

You get 3 repeated numbers because there are 3 numbers in second that are not in the orginal list.您会得到 3 个重复的数字,因为second个数字中有 3 个不在orginal列表中。

Testing测试

You can test this idea by expanding the lists您可以通过扩展列表来测试这个想法

original = [3, 6, 7, 9, 11, 14, 15]
second = [2, 6, 7, 10, 12, 15, 100, 200]

# print(c)
# [3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11, 14, 14, 14, 14, 14]

Now we have 5 unique values in the second list, so it's repeated 5 times now!现在我们在second列表中有 5 个唯一值,所以现在重复了 5 次!

This works:这有效:

[*filter(lambda x: x not in b, a)]

If you don't need to preserve order then you can use set.difference如果您不需要保留顺序,则可以使用set.difference

a = [3, 6, 7, 9, 11, 14, 15]
b = [2, 6, 7, 10, 12, 15]
c = set(a) - set(b)

Or if you want to use a comprehension:或者,如果您想使用理解:

c = [n for n in a if n not in b]
a = [3, 6, 7, 9, 11, 14, 15]
b = [2, 6, 7, 10, 12, 15]
c = []

for i in a:
    if i not in b:
        c.append(i)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM