Efficient way to combine two lists with a list or None

I have two lists that can be listor None. I want to get a third list with the result of a unique combination of these two lists.

  • If the firstlist is No and second No , there resultwill be No
  • If first No and secondnot No - resultwillsecond
  • If second No and firstnot No - resultwillfirst
  • If secondnot No and firstnot No - there resultwill befirst + second

I do this simply with the condition:

result = first if first else second
if result is not None:
    try:
        result = list(set(first + second))
    except TypeError:
        pass

I want to make it better. Perhaps you know how to solve this problem with one or more lines, using itertoolsor something else. If there is no way to solve this problem with another (more efficient) option, please do not deal with it, just say it.

Thanks for all the tips!

+4
source share
2 answers

A single line solution using itertools.chain.from_iterable could be:

set(itertools.chain.from_iterable((first or [], second or [])))

EDIT:

I made several timings of various solutions, here is what I get (on my computer using python3.6), for 10,000 iterations for 2 lists of 10,000 elements:

  • OP path: 7.34 s
  • raw set way (comment from @myaut:) set((first or []) + (second or [])): 5.95 s
  • itertools way: 5.69 s

, itertools , chain , + :).

+2

, : None, , :

def concat(l1, l2):
    if l1 is None and l2 is None:
        return None
    elif l1 is None:
        l1 = []
    elif l2 is None:
        l2 = []

    s = set(l1 + l2)

    return  s

:

>>> concat(None, None) is None
True
>>> concat([1,2,3], None)
set([1, 2, 3])
>>> concat(None, [4,5])
set([4, 5])
>>> concat([1,2,3], [4,5])
set([1, 2, 3, 4, 5])
>>> concat([1,2,3], [])
set([1, 2, 3])
>>> concat([], [])
set([])

, , .

0

Source: https://habr.com/ru/post/1686218/


All Articles