【问题标题】:List of products of values for all keys that match in two dictionaries两个字典中匹配的所有键的值的产品列表
【发布时间】:2011-09-16 09:49:18
【问题描述】:

我有两个字典形式的哈希表。键将特征映射到所述特征的出现列表。

a_dict = {'a': [1,2], 'b': [2,], 'c': [1,3]}
b_dict = {'a': [6], 'c': [4]}

我需要的是列表,或者理想情况下是一个 numpy 数组,其中包含两个匹配特征的所有出现组合。所以在这种情况下:

result = [[1,6],
          [2,6],
          [1,4],
          [3,4]]

由于这在某些时候应该在大型 dicts 上尽可能快地运行,所以我希望使用理解,因为 cython 可以理解它们。但他们只把我带到了这里:

>>> [itertools.product(value, a_dict[key]) for key,value in b_dict.items()]
[<itertools.product object at 0x1004a2960>, <itertools.product object at 0x1004a29b0>]

感谢您的帮助!

【问题讨论】:

  • 对了,会不会有只存在于b_dict的项目?
  • 是的。这几乎可以保证。

标签: python list dictionary cython


【解决方案1】:
import numpy as np
import itertools

a_dict = {'a': [1,2], 'b': [2,], 'c': [1,3]}
b_dict = {'a': [6], 'c': [4]}

print(list(itertools.chain.from_iterable(
    itertools.product(value, b_dict[key]) for key,value in a_dict.iteritems()
    if key in b_dict)))
# [(1, 6), (2, 6), (1, 4), (3, 4)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 2021-01-10
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2020-03-31
    相关资源
    最近更新 更多