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

2024-09-29 17:19:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用另一个列表中间的值替换一个列表中间的值。你知道,如果它在0和1之间,它就在中间。我想最好以最低的big-o复杂度来做这件事,因为我想重复它数千次

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]

Tags: orofthetol1middle列表that
3条回答

在我的机器上,这个实现比你的实现快了大约25%,并且仍然给出了完全相同的结果。你知道吗

s = None
for i,v in enumerate(l1):
    if v <= 0:
        continue  
    elif v < 1:
        if s:
            continue
        s = i
    else:
        l3 = l2[:s] + l1[s:i] + l2[i:]
        break

你可以试试这个。你知道吗

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]
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]

l3 = [ l2[a[0]] if a[1] in [0.0, 1.0] else a[1] for a in enumerate(l1) ]


print (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]

或者你可以用拉链

l4 = [a[1] if a[0] in [0.0, 1.0] else a[0] for a in zip(l1,l2)]

print (l4)

#[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]

对于包含数百个元素的列表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)

相关问题 更多 >

    热门问题