【问题标题】:Python - Extract dictionary value based on matching list and nested setPython - 根据匹配列表和嵌套集提取字典值
【发布时间】:2021-07-10 12:08:10
【问题描述】:

我正在努力获得我想要的输出。我有一个列表和一个字典,如下图所示:

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]}

如果嵌套列表的第一个索引与字典键匹配,我想将值附加到嵌套列表。我要附加的值是通过将嵌套列表的最后一个索引除以相应字典键的值来计算的。下面是我希望以第一个嵌套列表为例的手写示例。嵌套列表的第一个索引设置为“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) 

我在堆栈溢出中进行了广泛的研究,但我找不到任何东西。关于如何达到理想结果的任何想法?

【问题讨论】:

    标签: python pandas list dictionary key


    【解决方案1】:

    根据h3_rules的定义方式,那么首先需要验证第一个索引是否为set的实例,获取集合的第一个值,然后追加对应的除法即可。

    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])
        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 2021-05-10
      • 2021-02-12
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      相关资源
      最近更新 更多