我正在寻找最简单美观的方法来对这些列表进行乘法运算:
a = [True, False, True, False, False]
b = [100, 200]
a 中 True 元素的数量等于 b 的长度
我需要的答案是这里的 [100, 0, 200, 0, 0]
。有没有简单的方法得到这个答案?看起来像是逐元素相乘,但实际上第二个列表的大小较小,所以常规的numpy方法不起作用,需要进行复杂的编码。
希望您能找到一个好的解决方案。
我正在寻找最简单美观的方法来对这些列表进行乘法运算:
a = [True, False, True, False, False]
b = [100, 200]
a 中 True 元素的数量等于 b 的长度
我需要的答案是这里的 [100, 0, 200, 0, 0]
。numpy
来完成此操作:c = np.array(a).astype(int)
c[c==1] = b
>>> c
array([100, 0, 200, 0, 0])
注意 如果您需要按照所需输出将结果作为列表而不是numpy
数组返回,请使用 c.tolist()
有一种基于迭代器的相当简洁的解决方案
it = iter(b)
[next(it) if x else 0 for x in a]
# [100, 0, 200, 0, 0]
numpy
解决方案。 - AGN Gazernumpy
的解决方案更快。 - AGN Gazer另一种选择是使用 numpy.place()
或 numpy.put()
:
c = np.zeros_like(a, dtype=np.result_type(b))
np.place(c, a, b)
或者
c = np.zeros_like(a, dtype=np.result_type(b))
np.put(c, np.flatnonzero(a), b)
In [39]: a = np.random.randint(0, 2, 100000).astype(np.bool_)
In [40]: b = np.random.randint(0, 100000, np.sum(a))
@sacul的解决方案:
In [41]: %timeit c = np.array(a).astype(int); c[c==1] = b
621 µs ± 13.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
我的第一个选项:
In [42]: %timeit c = np.zeros_like(a, dtype=np.result_type(b)); np.place(c, a, b)
462 µs ± 8.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
c = np.zeros_like(a, dtype = b.dtype)
c[a] = b