简体   繁体   中英

How to add two lists together, avoid repetitions, and order elements?

I have two lists filled with integers. I wish to add them together such that:

  1. the output list has no duplicate elements,
  2. is in order, and
  3. contains the union of both lists.

Is there any way to do so without creating my own custom function? If not, what would a neat and tidy procedure look like?

For instance:

list1 = [1, 10, 2]
list2 = [3, 4, 10]

Output:

outputlist = [1, 2, 3, 4, 10]

Try this:

combined = [list1, list2]
union = list(set().union(*combined))

This takes advantage of the predefined method ( .union() ) of set() , which is what you need here.

combined can have as many elements inside it, as the asterisk in *combined means that the union of all of the elements is found.

Also, I list() ed the result but you could leave it as a set() .

As @glibdud states in the comments, it's possible that this might produce a sorted list, but it's not guaranteed, so use sorted() to ensure that it's ordered. (like this union = sorted(list(set().union(*combined))) )

l1 = [1, 10, 2]
l2 = [3, 4, 10]

sorted(list(set(l1 + l2)))
>>> [1, 2, 3, 4, 10]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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