将所有连续的都压入python列表中 [英] squash all consecutive ones in a python list

查看:48
本文介绍了将所有连续的都压入python列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用 0s 1s 填充的变量列表,例如:

I have variable lists filled with 0s and 1s, like:

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

什么是创建新列表以压缩所有连续 1s 的最有效方法.

what is the most efficient way to create new lists that squash all consecutive 1s.

因此结果将是:

l1_new = [1,0,1]
l2_new = [0,1,0,1,0,0,1]

提示:numpy/向量化或某些逻辑运算会很棒!

Hint: numpy/vectorization or some logical operation would be great!

推荐答案

这是与 np.diff 按位运算:

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

a = np.array(l2)
a[~((np.diff(a,prepend=False)==0) & (a==1))]
# array([0, 1, 0, 1, 0, 0, 1])

或者对于第一个示例:

a = np.array(l1)
a[~((np.diff(a,prepend=False)==0) & (a==1))]
#array([1, 0, 1])

这篇关于将所有连续的都压入python列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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