在实现一个产品过程中,使用 Python Extension 需要一个语句将一个列表中子列表合并成为一个新的列表,譬如:
原始列表为 [ 1, [2, 3], 4, [5, 6], 7 ], 需要使用一个表达式合并成为 [1, 2, 3, 4, 5, 6, 7]
经过多方组合,终于找到一个方式,使用 lambda 和 reduce 来实现:
reduce(lambda x, y: x.extend(y) or x, [ i if isinstance(i, list) else [i] for i in [0, 1, [2,3], 4]])
语句分析:
[ i if isinstance(i, list) else [i] for i in [0, 1, [2,3], 4]] 首先将列表转换成为元素全部为列表类型,执行结果如下
[ [0], [1], [2,3], [4] ]
lambda x, y: (x.extend(y) or x) 语句的作用是把列表 y 中元素追加到列表 x 中,并返回 x 的值。因为列表的 extend 方法返回的总是 None,所以这里使用 or 来返回第二个表达式的值。
reduce 函数是针对列表中所有元素,依次使用前面的 lambda 进行合并,最后输出一个列表。
组合成为上面的一个表达式,就实现了需要的功能。
约束:这个表达式只能展开一层子列表,对多层列表([ [ [1] ], 2]) 不适用。
补充:如何想要过滤重复的元素,在增加一个 set 调用即可,也就是
set(reduce(lambda x, y: x.extend(y) or x, [ i if isinstance(i, list) else [i] for i in [0, 1, [2,3], 4]]))
如果还是想返回一个 list 类型,在增加一个 list 调用进行转换
list(set(reduce(lambda x, y: x.extend(y) or x, [ i if isinstance(i, list) else [i] for i in [0, 1, [2,3], 4]])))