按位或减少python列表 [英] bitwise OR reduction of python lists

查看:108
本文介绍了按位或减少python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个零和一的列表.两个列表的长度相同.以下仅是示例,我正在寻找一种通用解决方案,以解决任何大小的列表以及在任何索引处带有零和一的问题.

I have two lists of zeros and ones. Both lists are of same length. The following is just an example, i am looking for a generic solution for lists of any sizes and with zeros and ones at any index.

l1 = [1,1,0,1,1,1,1]
l2 = [0,0,0,1,0,0,0]

目标是使用第一个列表l1作为maskl2创建新列表l2_new,逻辑上OR合并l11的所有indize元素并采用元素保持不变,其中l10.

The goal is to use the first list l1 as mask to create a new list l2_new from l2 that logicaly OR merges all elements of indizes where l1 is 1 and adopts elements unchanged where l1 is 0.

这将导致:

l2_new = [0,0,1]

图形说明:

推荐答案

对于基于切片的OR-ing-

# Get slice start indices, needed for `np.bitwise_or.reduceat`
In [55]: idx = np.flatnonzero(np.r_[True,np.diff(l1)!=0])

In [56]: np.bitwise_or.reduceat(l2, idx)
Out[56]: array([0, 0, 1])

这篇关于按位或减少python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆