簡體   English   中英

Python - 根據匹配列表和嵌套集提取字典值

[英]Python - Extract dictionary value based on matching list and nested set

我正在努力獲得我想要的 output。 我有一個列表和字典,如下圖所示:

h3_rules = [[{'LA'}, {'KE'}, 0.9468308801441875], [{'KE'}, {'LA'}, 0.9650949173300674], [{'EH'}, {'LA', 'KE'}, 0.9136231884057971], [{'LA'}, {'EH', 'KE'}, 0.9468308801441875], [{'KE'}, {'LA', 'EH'}, 0.9650949173300674], [{'LA', 'EH'}, {'KE'}, 0.9471153846153846], [{'EH', 'KE'}, {'LA'}, 0.9650949173300674], [{'LA', 'KE'}, {'EH'}, 1.0], [{'EH'}, {'KE'}, 0.9466666666666667], [{'KE'}, {'EH'}, 1.0], [{'LA'}, {'EH'}, 0.99969960949234], [{'EH'}, {'LA'}, 0.9646376811594203]]

and

h3_S = {'EH': [0.33326893353941267], 'KE': [0.31549459041731065], 'LA': [0.321580370942813], 'PR': [0.029656105100463678]}

如果嵌套列表的第一個索引與字典鍵匹配,我想 append 嵌套列表的值。 我想要 append 的值是通過將嵌套列表的最后一個索引除以相應字典鍵的值來計算的。 下面是我希望以第一個嵌套列表為例的手寫示例。 嵌套列表的第一個索引設置為“LA”:

h3_rules = [[{'LA'}, {'KE'}, 0.9468308801441875, (0.9468308801441875/0.321580370942813], ...]

目前我有下面的代碼,但我堅持檢查列表值是否與鍵匹配並使用除法值。

# For every rule in rules
for i in h3_rules:
  # Check if the first index for every rule matches a dictionary key
  if h3_rules[i][0] == ?:
    # If there is a match append the newly calculated value based on the key value to the list
    h3_rules[i].append(h3_rules[i][-1] / ?)
  print(h3_rules) 

我在堆棧溢出中進行了廣泛的研究,但我找不到任何東西。 關於如何達到理想結果的任何想法?

根據h3_rules的定義方式,那么首先需要驗證第一個索引是否是一個set的實例,獲取該集合的第一個值,然后就是append對應的划分。

for h in h3_rules:
    first_element = next(iter(h[0])) if isinstance(h[0], set) else None
    if first_element is not None: h.append(h[-1]/h3_S[first_element][0])
    

暫無
暫無

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

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