我給了一個清單
myLIST=[34 , 54 , 65 , 76 , 88 , 23 , 56 , 76 , 43]
和一個包含 myLIST 在 sublist 中的索引號的串列(假設 myLIST 從索引 1 開始)
indexLIST=[{1,2,3} , {4,5,7} , {6,8,9}]
我的任務是根據 indexLIST 的子串列添加 myLIST 的索引
[{34 54 65} , {76,88,23} , {56,76,43}]
res=[153 ,187 , 175]
注意:indexLIST 的子串列是 python 集合
uj5u.com熱心網友回復:
所以首先你的indexLIST(set 2 should be {4, 5, 6}and set 3 {7, 8, 9})或者你的res(給定indexLIST的 is [153, 220, 142])有錯誤,否則你可以做這樣的事情:
res: list[int] = list()
for set in indexLIST:
tmp = 0
for idx in set:
tmp = myLIST[idx - 1]
res.append(tmp)
uj5u.com熱心網友回復:
我的方法是遍歷索引集,index_list然后將這些集映射到my_list. 然后我sum()可以計算每個值串列的總和:
my_list=[34 , 54 , 65 , 76 , 88 , 23 , 56 , 76 , 43]
index_list=[{1,2,3} , {4,5,7} , {6,8,9}]
result = [sum(map(lambda x: my_list[x-1], d)) for d in index_list]
print(result)
輸出:
[153, 220, 142]
uj5u.com熱心網友回復:
myLIST=[34 , 54 , 65 , 76 , 88 , 23 , 56 , 76 , 43]
indexLIST=[{1,2,3} , {4,5,6} , {7,8,9}]
from pprint import pprint
pprint([sum([myLIST[j-1] for j in i])for i in indexLIST])
結果:
[153, 220, 142]
附言
您嘗試實作的這種型別的索引可能非常脆弱,例如,如果您提供的索引在您的串列中不存在怎么辦 ->IndexError ...?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/437629.html
