我想用另一个列表中间的值替换一个列表中间的值。你知道,如果它在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]
在我的机器上,这个实现比你的实现快了大约25%,并且仍然给出了完全相同的结果。你知道吗
你可以试试这个。你知道吗
或者你可以用拉链
对于包含数百个元素的列表NumPy应该可以显著提高性能。你知道吗
对于以下示例数据:
将boolean array indexing与就地替换结合使用可使速度提高约10倍:
与您的解决方案相比:
相关问题 更多 >
编程相关推荐