簡體   English   中英

從嵌套列表中的 position 個元素創建字典

[英]Create dictionary from the position of elements in nested lists

我想使用每個列表列表中的 position 個元素創建一個字典。 每個嵌套列表的順序非常重要,必須保持不變。

原始嵌套列表和所需的字典鍵:

L_original = [[1, 1, 3], [2, 3, 8]]
keys = ["POS1", "POS2", "POS3"]

L_original創建的所需字典:

L_dictionary = {"POS1": [1, 2], "POS2": [1, 3], "POS3": [3, 8]}

到目前為止,我的代碼沒有滿足條件,並在每次迭代的else語句上結束。

for i in L_original:
    for key, value in enumerate(i):
        if key == 0:
            L_dictionary[keys[0]] = value
        if key == 1:
            L_dictionary[keys[1]] = value
        if key == 2:
            L_dictionary[keys[2]] = value
        else:
            print(f"Error in positional data processing...{key}: {value} in {i}")

我相信有一些更簡潔的方法可以用一些花哨的 python API 來解決這個問題,但其中一個直接的解決方案可能如下所示:

對於keys中的每個key ,我們從L_original的嵌套 arrays 中獲取與key具有相同索引的那些數字,即idx

L_original = [[1, 1, 3], [2, 3, 8]]
keys = ["POS1", "POS2", "POS3"]
L_dictionary = {}

for (idx, key) in enumerate(keys):
    L_dictionary[key] = []
    for items in L_original:
        L_dictionary[key].append(items[idx])

您的代碼轉到else ,因為這elseif key == 2相關,而不是與if的整個鏈相關。 因此,例如,如果key0 ,則流程轉到else ,因為0 != 2 要解決此問題,應將第二個和后續的if替換為elif 這將else與整個鏈相關聯:

if key == 0:
  # only when key is 0
elif key == 1:
  # only when key is 1 
elif key == 2:
  # only when key is 2
else:
  # otherwise (not 0, not 1, not 2)

在枚舉時使用列表理解

L_dictionary = dict()
for i, k in enumerate(keys):
    L_dictionary[k] = [x[i] for x in L_original]

或者干脆

L_dictionary = {k: [x[i] for x in L_original] for i, k in enumerate(keys)} 
L_original = [[1, 1, 3], [2, 3, 8]]
keys = ["POS1", "POS2", "POS3"]

b=[list(x) for x in zip(L_original[0], L_original[1])]
a={i:b[index] for index,i in enumerate(keys)}

首先,我剛剛通過將第一個嵌套列表的索引壓縮( 參見 zip )到其他嵌套列表的相同索引來創建一個新列表。

b 的 Output:[[1, 2], [1, 3], [3, 8]]

然后使用keys的索引創建了一個字典: b列表的索引。

Output of a: {'POS1': [1, 2], 'POS2': [1, 3], 'POS3': [3, 8]}

暫無
暫無

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

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