用布尔掩码合并两个python列表

时间:2018-08-01 14:47:19

标签: python

我有一个简单的python列表和一个布尔掩码。首先,该列表根据掩码分为两个列表,然后我想将这两个列表合并回原始列表,而无需复制/清空两个列表(排除使用.pop()或{{1 }})。足够简单,可以用pandas,np或冗长的代码实现。但是,我需要在列表中实现它。没有其他可能的库(像.copy()这样的库就可以了)。

问题:如何将两个带有遮罩的列表整洁地组合在一起,而又不混乱又没有np / pandas / etc?

最小示例:

itertools

现在将它们结合起来;我要解决的问题。以下是三种可行的但不合格的方法(第一种笨拙,第二种使用np,第三种空# some data x = [1.0,2.0,3.0,4.0] print('original list: {}'.format(x)) # a boolean mask mask = [True,False,False,True] print('boolean mask: {}'.format(mask)) # splitting based on the mask is easy enough xt = [xx for (xx,m) in zip(x,mask) if m] xf = [xx for (xx,m) in zip(x,mask) if not(m)] print('true mask of x: {}'.format(xt)) print('false mask of x: {}'.format(xf)) # --output-- # original list: [1.0, 2.0, 3.0, 4.0] # boolean mask: [True, False, False, True] # true mask of x: [1.0, 4.0] # false mask of x: [2.0, 3.0] xt):

xf

这感觉很容易实现,但是如果没有# Method 1: desired performance, but long-winded i=0 j=0 x_merge=[] for m in mask: if m: x_merge.append(xt[i]) i += 1 else: x_merge.append(xf[j]) j += 1 print('merging back together (clunky): {}'.format(x_merge)) # Method 2: in numpy it's not hard either import numpy as np x_merge2 = np.zeros(len(xt)+len(xf)) x_merge2[mask]=xt x_merge2[[not(m) for m in mask]]=xf print('merging back together (np): {}'.format(x_merge2)) # Method 3: clean, but empties xt and xf, which I can't do; copy/pop also no good x_merge3 = [xt.pop(0) if m else xf.pop(0) for m in mask] print('merging back together (pop): {}'.format(x_merge3)) # --output-- # merging back together (clunky): [1.0, 2.0, 3.0, 4.0] # merging back together (np): [1. 2. 3. 4.] # merging back together (pop): [1.0, 2.0, 3.0, 4.0] copy/poppd或类似的东西(根据周围代码中的类型约束是真正的要求;我无法将其投射回列表或类似内容)。有人可以告诉我该怎么做吗?

编辑:我在发布之前进行了搜索(没有运气),但是是的,答案包含在该帖子中:Merge two or more lists with given order of merging

1 个答案:

答案 0 :(得分:2)

方法3,但使用标准迭代器而不是弹出窗口。

xti, xfi= iter(xt), iter(xf)
merged = [next(xti) if m else next(xfi) for m in mask]

({xti.next()将起作用,但仅在python2中有效)