Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

python - Get only unique elements from two lists

If I have two lists (may be with different len):

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

result = [11,22,33,44]

im doing:

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

I'm getting

result = [11,22,33,44,4]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATE:

Thanks to @Ahito:

In : list(set(x).symmetric_difference(set(f)))

Out: [33, 2, 22, 11, 44]

This article has a neat diagram that explains what the symmetric difference does.

OLD answer:

Using this piece of Python's documentation on sets:

>>> # 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'}

I came up with this piece of code to obtain unique elements from two lists:

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

or slightly modified to return list:

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

Here:

  1. | operator returns elements in x, f or both
  2. & operator returns elements in both x and f
  3. - operator subtracts the results of & from | and provides us with the elements that are uniquely presented only in one of the lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...