【问题标题】:Python: Lookup keys which correspond to an item in a dictionary of listsPython:查找与列表字典中的项目相对应的键
【发布时间】:2017-04-28 22:33:51
【问题描述】:

问题陈述

给定一个列表字典,

key_to_list = {
    'one': [1, 3, 5, 7],
    'two': [2, 4, 6, 8],
    'three': [1, 2, 5, 6],
    'four': [2, 5, 7, 8]
}

创建从列表元素到其键的映射的最佳方法是什么?

list_element_to_keys = {
    1: {'one', 'three'},
    2: {'two', 'three', 'four'},
    3: {'one'},
    4: {'two'},
    5: {'one', 'three', 'four'},
    6: {'two', 'three'},
    7: {'one', 'four'},
    8: {'two', 'four'}
}

我的解决方案

from collections import defaultdict

list_element_to_keys = defaultdict(set)
for key, value in key_to_list.items():
    for item in value:
        list_element_to_keys[item].add(key)

想法

我的一个朋友建议可以使用 字典理解,但我一直遇到问题 因为多个键的列表包含一些相同的项目。

我也认为他们可能是一些 itertools 的魔法,可以提供帮助, 但我并不积极。

听写理解

在朋友的帮助下,我发现了一种有效的字典理解。

from itertools import chain
list_element_to_keys= { i: set(k for k,v in key_to_list.items() if i in v) for i in set(chain.from_iterable(key_to_list.values())) }

【问题讨论】:

标签: python dictionary list-comprehension itertools defaultdict


【解决方案1】:

你也可以这样做

d = {}; [d.setdefault(i,[]).append(k) for k,v in key_to_list.items() for i in v]
print d

这导致

{1: ['three', 'one'],
 2: ['four', 'three', 'two'],
 3: ['one'],
 4: ['two'],
 5: ['four', 'three', 'one'],
 6: ['three', 'two'],
 7: ['four', 'one'],
 8: ['four', 'two']}

【讨论】:

  • 要匹配请求的解决方案,它应该是d.setdefault(i,set()).add(k)。但是仅仅为了副作用做一个理解......我不知道。
  • 谢谢@MSeifert,我认为 OP 只需要映射。但无论如何,您的评论是值得赞赏的。
  • 我曾一度想出这一点,但就像 MSeifert 指出的那样,仅将理解用于副作用似乎有点不雅。如果我们只关心代码打高尔夫球,这绝对是一个好方法。
【解决方案2】:

您的解决方案很好,它有效,defaultdict 是解决此类问题的明显(好的)选择。

您可以改进的一件事是使用six.iteritems(key_to_list),这将使其在 Python2 上更快一些。

【讨论】:

    【解决方案3】:

    我在单语句嵌套理解中得到它:

    • 编译一组值(新键)
    • 对于该集合的每个元素,遍历原始键
    • 如果原始键的值列表中有新键, 将该字符串包含在新键的值列表中

    代码:

    list_element_to_keys = \
        {new_key : [old_key for old_key in key_to_list.keys() if new_key in key_to_list[old_key]] \
         for new_key in set([item for value_list in key_to_list.values() for item in value_list ])}
    
    print (list_element_to_keys)
    

    输出(添加换行符以帮助阅读):

    {1: ['one', 'three'], 2: ['two', 'four', 'three'],
     3: ['one'], 4: ['two'],
     5: ['four', 'one', 'three'], 6: ['two', 'three'],
     7: ['four', 'one'], 8: ['two', 'four']}
    

    【讨论】:

    • 这很好,但它似乎失去了一些清晰度。
    • 是的,它失去了清晰度。 OP 要求理解字典... :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2014-07-21
    • 2021-08-24
    • 1970-01-01
    • 2017-03-11
    • 2011-11-16
    相关资源
    最近更新 更多