python - 从一个列表替换另一个列表中间的值

标签 python arrays list indexing replace

我想用另一个列表中间的值替换一个列表中间的值。如果它介于 0 和 1 之间,您就知道它位于中间。我希望最好以最低的大复杂度来执行此操作,因为我想重复它数千次

l1 = [0.0,0.0,0.0,0.0,0.0,   0.3,0.4,0.4,0.5,0.6,   1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0]

#l1 is a list of numbers with unique values that are not 0.0 or 1.0 in the middle

l2 = [0.0,0.1,0.1,0.1,0.1,   0.1,0.2,0.3,0.4,0.4,   0.5,0.5,0.6,0.6,0.7,0.7,0.8,0.8,0.9,0.9]

#I want to replace the above middle values of l1 to the middle values of l2 to get l3

l3 = [0.0,0.1,0.1,0.1,0.1,   0.3,0.4,0.4,0.5,0.6,   0.5,0.5,0.6,0.6,0.7,0.7,0.8,0.8,0.9,0.9]

#given that I know nothing about how many middle values there are or where they are 

编辑:列表是固定长度并排序的

edit2:这是我丑陋的解决方案。可以改进吗?

stop0 = -1
stop0bool = True
stop1 = -1
for i in range(20):
  if stop0bool and l1[i] != 0.0:
    stop0 = i
    stop0bool = False
  if l1[i] == 1.0:
    stop1 = i
    break;
l3 = l2[0:stop0] + l1[stop0:stop1] + l2[stop1:20]

最佳答案

对于具有数百个元素的列表NumPy应该会给你带来显着的性能提升。

对于以下示例数据:

import numpy as np

size = 500
x, y = 10, 486
a = np.sort(np.random.rand(size))
a[:x] = 0
a[y:] = 1
b = np.sort(np.random.rand(size))

使用 boolean array indexing就地替换可将速度提高约 10 倍:

mask = (a > 0) & (a < 1)
b[mask] = a[mask]
# 4.5 µs ± 23.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

与您的解决方案相比:

# 74 µs ± 61.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

关于python - 从一个列表替换另一个列表中间的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59029029/

相关文章:

python - 在 Bokeh 中调整 matplotlib 标记大小?

python - python numpy数组操作+=线程安全吗?

c++ - 打印出结构数组的元素

Python3 属性错误 : 'list' object has no attribute 'clear'

c# - 如何在不使用 foreach 循环的情况下将列表的某些字段复制到另一个列表的某些字段?

python - 对于 MultinomialNB,Sklearn 偏向正值

Python:添加到列表中的字典

python - Groupby 多列和聚合与 dask

javascript - 在下面提到的场景中如何为爱好提供 typescript 类型?

python - 如何根据列表中类的属性使 Python 中的列表不同?