[英]Create a list with items from another list at indices specified in a third list
[英]Replace multiple items in a list of list from another list of list of indices and values
我在下面有一個 list1:
list1 = [[(0, 8), (2, 9), (3, 9)],
[(0, 10), (2, 9), (3, 9)],
[(0, 11), (2, 12), (3, 12)]]
此列表列表包含以索引作為第一項和值作為第二項的元組。 我需要用上面 list1 中的值替換下面 list2 中特定索引處的值。 list1 和 list2 的長度相同,列表列表中的索引將在以下范圍內:
list2 = [[[], [], [], [], [], [], []],
[[], [], [], [], [], [], []],
[[], [], [], [], [], [], []]]
預期的 output 是:
output = [[8, [], 9, 9, [], [], []],
[10, [], 9, 9, [], [], []],
[11, [], 12, 12, [], [], []]]
我嘗試了以下代碼:
def replist(x,y):
for i in x:
for m,n in i:
y[m]=n
output = [replist(list1, i) for i in list2]
output = [[11, [], 12, 12, [], [], []],
[11, [], 12, 12, [], [], []],
[11, [], 12, 12, [], [], []]]
我知道我的代碼存在問題,而且它不是以這種方式替換列表中項目的正確方法,但想知道是否有辦法進行替換。
我用一些類似的問題檢查了許多 stackoverflow 鏈接,但它們涉及替換單個列表。
您可以更改 function 本身以直接在列表上工作:
list1 = [[(0, 8), (2, 9), (3, 9)],
[(0, 10), (2, 9), (3, 9)],
[(0, 11), (2, 12), (3, 12)]]
list2 = [[[], [], [], [], [], [], []],
[[], [], [], [], [], [], []],
[[], [], [], [], [], [], []]]
def replist(input_list,output_list):
for list_index, entry in enumerate(input_list):
for sub_index, value in entry:
output_list[list_index][sub_index]=value
return output_list
output = replist(list1, list2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.