python - python列表中的变量扩展
问题描述
我有一个可变长度的 python 列表,其中填充了0s
and 1s
。
我想创建一个新列表,所有列表1s
都由某个offset
.
例子:
offset = 1
l1 = [0,0,1,0]
l1_new = l[0,1,1,1]
l2 = [1,0,0,0,1,0,1,0,0]
l2_new = [1,1,0,1,1,1,1,1,0]
我的解决方案代码不是很快,也没有使用任何 numpy / 矢量化 / 按位操作。但我想其中一些方法应该适用于这里。
offset = 1
l_old = [0,0,1,0]
l_new = []
for i,l in enumerate(l_old):
hit = False
for o in range(offset+1)[1:]:
if (i+o<len(l_old) and l_old[i+o]) or (i>0 and l_old[i-o]):
hit = True
break
if hit or l_old[i]:
l_new.append(1)
else:
l_new.append(0)
提示:解决方案应该是快速和通用的任何列表
0s
和1s
任何offset
解决方案
这是一个线性 (O(n+offset)) 时间解:
import numpy as np
def symm_dil(a,hw):
aux = np.zeros(a.size+2*hw+1,a.dtype)
aux[:a.size] = a
aux[2*hw+1:] -= a
return np.minimum(aux.cumsum(),1)[hw:-hw-1]
#example
rng = np.random.default_rng()
a = rng.integers(0,2,10)
print(a)
print(symm_dil(a,2))
样本输出:
[0 0 0 1 0 0 0 0 0 1]
[0 1 1 1 1 1 0 1 1 1]
推荐阅读
- python - 带有 python 脚本的 Docker 文件以获取进程输出的结束
- java - findAll 从 org.springframework.data.jpa.repository.support.SimpleJpaRepository 返回重复项
- graphql - GraphQL:如何防止数据库抓取?
- assembly - MIPS 代码不打印从内存加载的字符串
- docker - Liveness probe failed: Get http://192.168.9.69:8080/health: read tcp 10.9.44.118:44143->192.168.9.69:8080: read: connection reset by peer
- python - 在特定目录的上下文中运行 python unittest
- python - 更新 QLabel ,在 QDialog 中使用 QPushButton
- rest - 通过 Postman 访问 IBM API Connect 端点
- sql - 自联接和效率与子查询
- python - 权限错误:[errorno 13] 权限被拒绝 C:\\windows\\system 32 \drives\\etc