将两个列表与列表或 None 值合并的有效方法

Vla*_*lav 7 python algorithm list python-2.7 python-3.x

我有两个列表可以是listor None。我想获得第三个列表,其中包含这两个列表的唯一联合结果。

  • 如果first列表为None并且secondNone -result将为None
  • 如果firstNonesecond不是None -result将是second
  • 如果secondNonefirst不是None -result将是first
  • 如果second不是Nonefirst不是None -result将是first + second

我用 if 条件做这个简单的事情:

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

            
Run Code Online (Sandbox Code Playgroud)

我想以更好的方式做到这一点。也许您知道通过使用一个或多个字符串itertools或其他方法来解决此问题的方法。

Céd*_*ien 5

使用itertools.chain.from_iterable 的单行解决方案可以是:

set(itertools.chain.from_iterable((first or [], second or [])))
Run Code Online (Sandbox Code Playgroud)

编辑:

我对不同的解决方案进行了一些计时,以下是我获得的结果(在我的计算机上,使用 python3.6),对于 2 个 10000 个项目的列表进行 10000 次迭代:

  • OP方式:7.34秒
  • 原始设置方式(@myaut 的评论:)set((first or []) + (second or [])):5.95 s
  • itertools方式:5.69秒

所以 itertools 方法更快一点,该chain方法比列表运算符更好+:)。