如何重新排序嵌套串列中的元素?(蟒蛇 3)
我想從 y 中獲取值并將它們按 x 中的元素順序排列。之后,我需要按照確切的順序將我的結果放在另一個串列中。如何重新排序元素以獲得預期結果?這是我到目前為止所做的:
def make_lists(x,y):
b=[]
order=[]
for i in range(len(x)):
order.append(i)
for dic in y:
a=[]
for key in dic.keys():
for stuff in x:
if stuff==key:
a.append(dic[key])
b.append(a)
return b
print(make_lists(['Hint', 'Num'],
[{'Hint': 'Length 2 Not Required', 'Num' : 8675309},
{'Num': 1, 'Hint' : 'Use 1st param order'}]))
輸出
[['Length 2 Not Required', 8675309], [1, 'Use 1st param order']
預期的
[['Length 2 Not Required', 8675309], ['Use 1st param order', 1]
uj5u.com熱心網友回復:
這是執行此操作的另一種方法。它將適用于 x(第一個串列)中的 N 個元素,并在 dict y 中未預設鍵時添加“無”。
def make_lists(x, y):
result = []
for each_record in y:
result.append([each_record.get(each_order, None) for each_order in x])
return result
所有鍵都存在時的輸出:
print(make_lists(['Hint', 'Num'],
[{'Hint': 'Length 2 Not Required', 'Num' : 8675309},
{'Num': 1, 'Hint' : 'Use 1st param order'}]))
[['Length 2 Not Required', 8675309], ['Use 1st param order', 1]]
當其中一個鍵不存在時輸出:
print(make_lists(['Hint', 'Num'],
[{'Hint': 'Length 2 Not Required', 'Num' : 8675309},
{'Hint' : 'Use 1st param order'}]))
[['Length 2 Not Required', 8675309], ['Use 1st param order', None]]
uj5u.com熱心網友回復:
前面的答案很優雅。但是,如果你想以基本的方式做到這一點,這里是代碼。一個相當大的優勢是我們不假設密鑰存在于“訂單”串列中。如果該元素不存在,則在其位置附加“無”。
order = ['Hint', 'Num']
dictionaries = [{'Hint': 'Length 2 Not Required', 'Num' : 8675309},
{'Num': 1, 'Hint' : 'Use 1st param order'}]
def make_lists(x, y):
all_lists = [] # This is the final list that will be returned
# First, we loop through each dictionary
for dic in y:
list_ = []
# In each dictionary, we get the values in
# the right order and then append it to a list
for key in x:
required_value = dic.get(key)
list_.append(required_value)
# We finally append our list - which is in right order
# to another list that will be returned
all_lists.append(list_)
return all_lists
print(make_lists(order, dictionaries))
邏輯是遍歷字典。對于每個字典,您按正確的順序附加值。
輸出:
[['Length 2 Not Required', 8675309], ['Use 1st param order', 1]]
[["Hint", "Num"], ["Hint", "Num"]]
uj5u.com熱心網友回復:
一種使用方式operator.itemgetter:
注意:這假設鍵始終存在于目標字典中。
from operator import itemgetter
list(map(itemgetter("Hint", "Num"), dicts))
或者只是使用 列出理解dict.get,以便它可以處理丟失的鍵:
[[d.get(k) for k in keys] for d in dicts]
輸出:
[('Length 2 Not Required', 8675309), ('Use 1st param order', 1)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/347426.html
上一篇:我對串列中的字典有問題
下一篇:使用兩個串列洗掉專案
