【问题标题】:Nested list with dictionary as content以字典为内容的嵌套列表
【发布时间】:2014-04-01 07:49:01
【问题描述】:

您好,我怎样才能遍历下面的 lst2,如果元素匹配,则在 lst1 中获取字典元素。

lst1 = [[(10, 70, {'a': 0.30}),
         (12, 82, {'b': 0.35})],
        [(11, 140, {'c': 0.54}),
         (99, 25, {'d': 0.57})]
       ]

lst2 = [[(10, 70), (32, 25),(12,82)],
        [(1598, 6009), (11,140), (33,66), (99,25)]
       ]

即比较 lst2,如果 lst2 在 lst1 中,则打印字典。

结果应该是这样的:

outcome = [[{'a': 0.30}, {'b':0.35}], [{'c': 0.54}, {'d':0.57}]]

谢谢

很抱歉,如果 lst1 没有嵌套,则对此进行更新,即

lst1 = [(10, 70, {'a': 0.30}),
        (12, 82, {'b': 0.35}),
        (11, 140, {'c': 0.54}),
        (99, 25, {'d': 0.57})
       ]

lst2 = [[(10, 70), (32, 25),(12,82)],
        [(1598, 6009), (11,140), (33,66), (99,25)]
       ]

这样会得到同样的结果

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以展平lst1 并将其转换为具有字典理解的字典,以便查找更快。字典构建完成后,只需迭代lst2,如果元素是字典中的键,则获取对应的字典值。

    from itertools import chain
    d = {(item[0], item[1]):item[2] for item in chain.from_iterable(lst1)}
    print d
    # {(12,82):{'b':0.3}, (10,70):{'a':0.3}, (11,140):{'c':0.54}, (99,25):{'d':0.57}}
    print [[d[item] for item in items if item in d] for items in lst2]
    # [[{'a': 0.3}, {'b': 0.3}], [{'c': 0.54}, {'d': 0.57}]]
    

    如果输入不是嵌套的,就像在更新的问题中一样,您不需要链接。你可以简单地做

    d = {(item[0], item[1]):item[2] for item in lst1}
    

    【讨论】:

    • ` d = { (item[0], item[1]) : item[2] for item in chain.from_iterable(lst1) } ^ SyntaxError: invalid syntax`
    • 我在 Python 2.6 中运行代码,当我在 Python 2.7 中运行时,就可以了。
    • @BlackMamba 哦,是的,Python 2.6 中没有引入字典理解。试试这个d = dict(((item[0], item[1]), item[2]) for item in lst1)
    【解决方案2】:

    对于每一对,为lst1 中的元素创建一个dict(用于性能),然后检查lst2 中的每个元素。

    outcome = []
    for lst_a, lst_b in zip(lst1, lst2):
        lookup = {a[:-1]:a[-1] for a in lst_a}
        outcome.append([lookup[b] for b in lst_b if b in lookup])
    print outcome
    

    【讨论】:

      猜你喜欢
      • 2022-12-05
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多