簡體   English   中英

從另一個列表替換一個列表中間的值

[英]Replacing values in the middle of one list from another list

我想用另一個列表中間的值替換一個列表中間的值。 如果它在 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 

編輯:列表是固定長度和排序的

編輯2:這是我丑陋的解決方案。 可以改進嗎?

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

使用帶有就地替換的布爾數組索引可將速度提高約 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)

你可以試試這個。

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]

或者你可以使用 zip

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]

這個實現比我機器上的快 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM