从两个列表python中只获取唯一元素

时间:2015-02-11 00:36:19

标签: python list unique

如果我有两个列表(可能有不同的len):

x = [1,2,3,4]
f = [1,11,22,33,44,3,4]

result = [11,22,33,44]
我正在做:

for element in f:
    if element in x:
        f.remove(element)

我得到了

result = [11,22,33,44,4]

10 个答案:

答案 0 :(得分:19)

如果你想要两个列表中的唯一元素,这应该有效:

x = [1,2,3,4]
f = [1,11,22,33,44,3,4]

res = list(set(x+f))
print(res)
# res = [1, 2, 3, 4, 33, 11, 44, 22]

答案 1 :(得分:12)

基于new (closed) question中对此问题的澄清:

如果您希望第二个列表中的所有项目都没有出现在第一个列表中,您可以写下:

x = [1,2,3,4]
f = [1,11,22,33,44,3,4]

result = set(f) - set(x) # correct elements, but not yet in sorted order
print(sorted(result)) # sort and print

# Output: [11, 22, 33, 44]

答案 2 :(得分:6)

在场景中使用这段Python's documentation

>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}

我想出了这段代码来从两个列表中获取唯一元素:

(set(x) | set(f)) - (set(x) & set(f))

或稍作修改以返回list

list((set(x) | set(f)) - (set(x) & set(f))) #if you need a list

这里:

  1. |运算符返回xf两者
  2. 中的元素
  3. &运算符返回 xf
  4. 中的元素
  5. -运算符从&中减去|的结果,并向我们提供仅在列表之一中唯一显示的元素

答案 3 :(得分:4)

如果您只想从两个列表中获取唯一元素,那么您可以通过..

获取它
a=[1,2,3,4,5]
b= [2,4,1]
list(set(a) - set(b))
OP:- [3, 5]

答案 4 :(得分:4)

x = [1, 2, 3, 4]

f = [1, 11, 22, 33, 44, 3, 4]

list(set(x) ^ set(f))

[33, 2, 22, 11, 44]

答案 5 :(得分:2)

输入:

x = [1,2,3,4]

f = [1,11,22,33,44,3,4]

代码:

l = list(set(x).symmetric_difference(set(f)))
print(l)

输出:

[2, 22, 33, 11, 44]

答案 6 :(得分:0)

您的方法不会获得唯一元素“2”。怎么样:

list(set(x).intersection(f))

答案 7 :(得分:0)

v_child_value = [{'a':1}, {'b':2}, {'v':22}, {'bb':23}]
shop_by_cat_sub_cats = [{'a':1}, {'b':2}, {'bbb':222}, {'bb':23}]


unique_sub_cats = []
for ind in shop_by_cat_sub_cats:
    if ind not in v_child_value:
        unique_sub_cats.append(ind)
  

unique_sub_cats = [{' bbb':222}]

答案 8 :(得分:0)

Python代码从两个列表创建唯一列表:

a=[1,1,2,3,5,1,8,13,6,21,34,55,89,1,2,3]
b=[1,2,3,4,5,6,7,8,9,10,11,12,2,3,4]
m=list(dict.fromkeys([a[i] for i in range(0,len(a)) if a [i] in a and a[i] in b and a[i]]))

print(m)

答案 9 :(得分:-1)

L=[] 
For i in x:
    If i not in f:
        L. Append(I)
For i in f:
    If I not in x:
        L. Append(I)
Return L