[英]how to create a list of values from one key-value pair based on the value of another k-v pair from a list of dictionaries with two key-value pairs
[英]How to access values from a dictionary inside a list based on another key-value pair?
鑒於下面的列表,
graph = [{'Node':'A', 'children':['T','Z','S'], 'gWt':[118,75,140], 'h':366},
{'Node':'Z', 'children':['O','A'], 'gWt':[71,75], 'h':374},
{'Node':'T', 'children':['A'], 'gWt':[118], 'h':329},
{'Node':'S', 'children':['A','O','R','F'], 'gWt':[140,151,80,99], 'h':253}]
對於給定的節點值,我將如何獲得它的所有“孩子”? 例如,
graph.index('Node'=='S')['children'] -> ['A','O','R','F']
index()
或next()
的評論: 創建節點名稱列表,然后使用index()
查找節點的索引是 go 的方法,但請注意,這可能導致性能大幅下降以及邏輯錯誤。
list.index(target)
在列表中查找是O(n) ,這意味着它遍歷列表中的每個元素,直到找到與不理想的目標匹配的第一個元素。graph = [{"node": "A", ...props1}, {"node": "A", ... props2}]
,由於index()
function 的性質,您只會遇到第一個節點。 如果您想找到每個節點"A"
,那么您需要在所有列表上運行index()
,直到您確定找到所有節點"A"
,然后考慮節點屬性的合並策略。使用字典存儲圖的節點。 字典具有恆定的時間查找 ( O(1) ),因為它們是hash 表。 您希望實現的表示是:
graph = {
"A": {'children':['T','Z','S'], 'gWt':[118,75,140], 'h':366},
"B": {'children':['O','A'], 'gWt':[71,75], 'h':374},
...
}
這也將使您的圖表的遍歷變得超級容易。 這樣,每當您在尋找節點"X"
時,您只需要graph["X"]
來獲取它,並且graph["X"]["children"]
來獲取它的子節點。
如果您無法構建上述數據結構,那么如果您打算不斷查詢圖形的節點屬性,那么您肯定希望將其轉換為最佳結構。 您可以通過以下方式實現:
def transform_graph(graph):
new_graph = {}
for node in graph:
node_name = node['Node']
new_graph[node_name] = new_graph.get(
node_name,
{'children': set(), 'gWt': set(), 'h': 0}
)
new_graph[node_name]["children"] |= set(node['children'])
new_graph[node_name]["gWt"] |= set(node["gWt"])
new_graph[node_name]["h"] = node["h"]
return new_graph
調用 function transform_graph(old_graph)
的 output 是
old_graph = [
{'Node':'A', 'children':['T','Z','S'], 'gWt':[118,75,140], 'h':366},
{'Node':'Z', 'children':['O','A'], 'gWt':[71,75], 'h':374},
{'Node':'T', 'children':['A'], 'gWt':[118], 'h':329},
{'Node':'S', 'children':['A','O','R','F'], 'gWt':[140,151,80,99], 'h':253}
]
new_graph = transform_graph(old_graph)
print(new_graph)
> {
'A': {'children': {'S', 'T', 'Z'}, 'gWt': {75, 118, 140}, 'h': 366},
'Z': {'children': {'A', 'O'}, 'gWt': {71, 75}, 'h': 374},
'T': {'children': {'A'}, 'gWt': {118}, 'h': 329},
'S': {'children': {'A', 'F', 'O', 'R'}, 'gWt': {80, 99, 140, 151}, 'h': 253}
}
假設只有一個值等於'S'
,您可以使用next :
graph = [{'Node':'A', 'children':['T','Z','S'], 'gWt':[118,75,140], 'h':366},
{'Node':'Z', 'children':['O','A'], 'gWt':[71,75], 'h':374},
{'Node':'T', 'children':['A'], 'gWt':[118], 'h':329},
{'Node':'S', 'children':['A','O','R','F'], 'gWt':[140,151,80,99], 'h':253}]
result = next(e for e in graph if e['Node'] == 'S')['children']
print(result)
Output
['A', 'O', 'R', 'F']
我喜歡你的數據可能是最好的格式,但這確實有效:
graph[[x['Node'] for x in graph].index('S')]['children']
將打印
['A', 'O', 'R', 'F']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.