python - 将两个列表与列表或无值合并的有效方法

标签 python algorithm python-2.7 python-3.x list

我有两个列表,可以是listNone。我想获得第三个列表,其结果是将这两个列表唯一结合起来。

  • 如果 first 列表是 None 并且 secondNone - result 将是
  • 如果 firstNone 并且 second 不是 None - result 将成为第二
  • 如果 secondNone 并且 first 不是 None - result 将成为第一
  • 如果second 不是None 并且first 不是None - 结果将是 first + second

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

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

            

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

最佳答案

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

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

编辑:

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

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

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

关于python - 将两个列表与列表或无值合并的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46367233/

相关文章:

python - 将 dask.array 列添加到 dask.dataframe

python - TypeError : '<' not supported between instances of 'function' and 'str'

arrays - 在常量内存空间中应用排列的算法

python - if/elif 语句的多个条件

python - 如何在 python 类上创建带参数的装饰函数?

python - 如果在数组创建期间定义了 NumPy 数组的元素,为什么 Cython 需要更多 Python 调用?

python - 根据条件分隔列表项 - Python

python cmd模块退出快捷方式

algorithm - 如何将此排序算法转换为 mips 程序集

c - Dijkstra,Bellman Ford 在双阵列 map 上的应用