簡體   English   中英

基於元組列表(值,索引)創建列表

[英]Create a list based on list of tuples (value, indices)

我輸入了一個帶有字符串和整數列表的元組列表。 整數從1n ,最多出現一次:

l = [('red', [0,2,5]),
     ('yellow', [1,4]),
     ('red', [6])]

我想創建一個n字符串的列表,如果索引出現在其中一個列表中,它的值將是相應的字符串,如果它沒有出現,將應用默認值,例如white

這是預期的輸出:

result = ['red', 'yellow', 'red', 'white', 'yellow', 'red', 'red']

這是我的代碼,它工作正常,但我想知道是否有更快的方法來做到這一點

result = ['white'] * n

for t in l:
    for i in t[1]:
        result[i] = t[0]

編輯:

我忘了說n大概是300。

對於所有“有更快的方法來做這個”的問題在python中(而且,我相信,在大多數語言中),答案是衡量它,然后你就會知道

我在目前為止提出的答案中采用了代碼,並將其計時:

import numpy as np
import timeit

n = 7
l = [('red', [0,2,5]),
     ('yellow', [1,4]),
     ('red', [6])]

def OP_approach():
    result = ['white'] * n
    for t in l:
        for i in t[1]:
            result[i] = t[0]
    return result

def yatu_approach():
    d = {j:i[0] for i in l for j in i[1]}
    return [d.get(i, 'white') for i in range(len(d)+1)]

def blue_note_approach():
    x = np.empty(7, dtype='<U5')
    x.fill('white')
    for a, b in l:
        x[b] = a
    return x

timeit.timeit(OP_approach, number=10000)
timeit.timeit(yatu_approach, number=10000)
timeit.timeit(blue_note_approach, number=10000)

令我驚訝的是,這是我的機器(arm64板)上的結果:

>>> timeit.timeit(OP_approach, number=10000)
0.033418309001717716
>>> timeit.timeit(yatu_approach, number=10000)
0.10994336503790691
>>> timeit.timeit(blue_note_approach, number=10000)
0.3608954470255412

那么,似乎對於給定的樣本數據,簡單的雙循環比其他兩個選項更快。 但請記住,正如@yatu所指出的那樣,這些算法的擴展方式非常不同,選擇哪種算法取決於要解決的問題的預期大小。

只有使用numpy

import numpy as np
x = np.empty(7, dtype='<U6')
x.fill('white')

for a, b in l:
    x[b] = a

其中U6表示長度為6(最多)的unicode字符串

from operator import itemgetter

l = [('red', [0,2,5]),
     ('yellow', [1,4]),
     ('red', [6])]
# get len of result
n = max(l, key = itemgetter(1))[1] 

# initialize the result list
result = ['white'] * 7

for t in l:
    for i in t[1]:
        result[i] = t[0]

輸出:

result = ['red', 'yellow', 'red', 'white', 'yellow', 'red', 'red']

暫無
暫無

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

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