Python 从另一个列表中替换一个列表中间的值
我想用一个列表中间的值替换另一个列表中间的值。你知道它在中间,如果它在0和1之间。我希望最好以最低的big-o复杂度来做这件事,因为我想重复它数千次Python 从另一个列表中替换一个列表中间的值,python,arrays,list,indexing,replace,Python,Arrays,List,Indexing,Replace,我想用一个列表中间的值替换另一个列表中间的值。你知道它在中间,如果它在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
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]
你可以试试这个
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]
对于包含数百个元素的列表,应该可以显著提高性能 对于以下示例数据:
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))
与就地更换一起使用可使速度提高约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)
在我的机器上,此实现比您的实现快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
你的真实名单有多大?与您的示例大小相似还是更大?是否可以就地执行替换,或者您始终需要创建新列表?您到底需要重复数千次什么,包括查找索引和创建新列表,还是只查找一次索引,然后用相同的索引替换数千个其他数组?真正的列表有数百个长度。无论什么过程都不重要,我只需要一个结果列表,该列表与我在L3中存储的列表相同。列表总是排序的吗?列表的长度是否总是相同的?这是可行的,但我用我的代码运行了它,实际上速度较慢。我不知道哪一个更快,但你也可以试试zip版本。这是最快的解决方案
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