【问题标题】:Getting all combinations of key/value pairs in Python dict在 Python dict 中获取键/值对的所有组合
【发布时间】:2012-08-10 16:17:59
【问题描述】:

这可能是一个愚蠢的问题,但鉴于以下 dict:

combination_dict = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}

我将如何实现这个列表:

result_list = [{"one": [1, 2, 3], "two": [2, 3, 4]}, {"one": [1, 2, 3], "three": [3, 4, 5]}, {"two": [2, 3, 4], "three": [3, 4, 5]}]

换句话说,我想要一个字典中两个键/值对的所有组合,而不考虑顺序。

【问题讨论】:

  • 为什么你的result_list中没有"two"/"three"
  • 感谢您指出这一点!

标签: python list dictionary combinations


【解决方案1】:

一种解决方案是使用itertools.combinations():

result_list = map(dict, itertools.combinations(
    combination_dict.iteritems(), 2))

编辑:由于popular demand,这里是Python 3.x 版本:

result_list = list(map(dict, itertools.combinations(
    combination_dict.items(), 2)))

【讨论】:

  • +1。除非有特别的理由不这样做,否则我倾向于使代码在 python 2 和 3 之间更具可移植性。我会使用dict.items()除非存在内存问题。
  • @JoelCornett 如果您正在考虑使用 3.x,那么您还必须将 map 对象转换为 list,因此最好将此作为注释
  • @JoelCornett:是的,很好。我想如果我使用items() 而不是iteritems(),有人会评论说这会浪费内存。 (老实说,如果字典太大以至于复制指向所有键和值的指针是一个问题,那么您当然不希望创建两个项目的所有组合,这会使用 O(n²) 额外空间。)
  • @JollyJumper:你是对的:p。尽管如此,为了完整起见,在 2.x 之下包含 3.x 版本可能会很有用。
【解决方案2】:

我更喜欢@JollyJumper 的解决方案以提高可读性,尽管这个解决方案执行得更快

>>> from itertools import combinations
>>> d = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}
>>> [{j: d[j] for j in i} for i in combinations(d, 2)]
[{'three': [3, 4, 5], 'two': [2, 3, 4]}, {'three': [3, 4, 5], 'one': [1, 2, 3]}, {'two': [2, 3, 4], 'one': [1, 2, 3]}]

时间安排:

>python -m timeit -s "d = {'three': [3, 4, 5], 'two': [2, 3, 4], 'one': [1, 2, 3]}; from itertools import combinations" "map(dict, combinations(d.iteritems(), 2))"
100000 loops, best of 3: 3.27 usec per loop

>python -m timeit -s "d = {'three': [3, 4, 5], 'two': [2, 3, 4], 'one': [1, 2, 3]}; from itertools import combinations" "[{j: d[j] for j in i} for i in combinations(d, 2)]"
1000000 loops, best of 3: 1.92 usec per loop

【讨论】:

    【解决方案3】:
    from itertools import combinations
    combination_dict = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]}
    lis=[]
    for i in range(1,len(combination_dict)):
        for x in combinations(combination_dict,i):
            dic={z:combination_dict[z] for z in x}
            lis.append(dic)
    print lis            
    

    输出:

    [{'three': [3, 4, 5]}, {'two': [2, 3, 4]}, {'one': [1, 2, 3]}, {'three': [3, 4, 5], 'two': [2, 3, 4]}, {'three': [3, 4, 5], 'one': [1, 2, 3]}, {'two': [2, 3, 4], 'one': [1, 2, 3]}]
    

    【讨论】:

      【解决方案4】:

      我相信这会让你得到你所需要的。

      result list = [{combination_dict['one','two'],combination_dict['one','three']}]
      

      我发现这个教程很有帮助:

      http://bdhacker.wordpress.com/2010/02/27/python-tutorial-dictionaries-key-value-pair-maps-basics/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-06
        • 2018-10-22
        • 1970-01-01
        • 1970-01-01
        • 2023-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多