我有两个列表,可以是list
或None
。我想获得第三个列表,其结果是将这两个列表唯一结合起来。
- 如果
first
列表是 None 并且second
是 None -result
将是无 - 如果
first
是 None 并且second
不是 None -result
将成为第二
- 如果
second
是 None 并且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/