【问题标题】:itertools.permutations for a set of dicts一组 dicts 的 itertools.permutations
【发布时间】:2021-09-29 09:32:15
【问题描述】:

在我问我的问题之前,我想让你们知道我是一个初学者编码器,我感谢所有输入,所以提前感谢你的帮助。

假设我有以下对象:

set: [
       {'id': 1
        'type': a
       },

       {'id': 2
        'type': a
       },

       {'id': 3
        'type': b
       },

       {'id': 4
        'type': b
       },

       {'id': 5
        'type': a
       }
]

我如何使用itertools.permutations 来计算(并最终复制)'type' 键的所有组合?即有一个集合,其中 id 3 和 5 的类型为 b,其余为 a,其中 id 2 和 5 的类型为 b,其余为 a,等等。

此外,是否可以在特定条件下计算组合(例如,对于所有组合,id 1 和 2 必须始终为 a 类型)?

提前谢谢大家

【问题讨论】:

  • 你想要的输出是什么?你的意思是set_list = [ {'id... 而不是set: [ {'id
  • 那么,您在寻找“aaaaa”、“aaaab”、“aaaba”、“aaabb”等吗?会有 32 个这样的组合,如果只有 3 个点,则有 8 个。你的套装有多大?
  • 你不能有一套字典。
  • 欢迎来到 Stack Overflow!请使用tour 并阅读How to Ask。我想回答你的问题,但不清楚。首先,dict 项缺少逗号,这会导致 SyntaxError。一旦你解决了这个问题,ab 就不会被定义。然后,它不是真正的 Python 对象,它是变量名称 setannotation 作为该列表。最后,你想要的输出是什么?请edit澄清。
  • 您不能将 dicts 放入集合中,因为它们是可变的。所以这可能会有所帮助:What would a “frozen dict” be?

标签: python dictionary key-value itertools


【解决方案1】:

您可以使用列表推导来提取所有 "type" 值,然后您可以将它们推送到 set(或将其留在 list 中)以计算排列。

from itertools import permutations

typeset = [...]  # what you named `set` in the question
types = [d["type"] for d in typeset]

# Optionally, push `types` through a `set` to get only the unique `type` values
# types = set(types)

combos = list(permutations(types, r=None))

如果你还没有看过,here's a link to the docs on permutationsr 完全是可选的,但它可以让您计算长度排列 r 而不是 len(types)


或者,让我们考虑一下您想要List[Dict] 的排列的情况:

from itertools import permutations

typeset = [...]  # as before
types = range(len(typeset))

combos = list(permutations(types, r=None))

您现在可以根据combos 中存储的索引检索typeset 的所有排列。但是,根据您的typeset 的大小,我不推荐它,因为这会消耗相当多的内存。

【讨论】:

    【解决方案2】:

    what John already has 的基础上,我们可以通过在计算排列之前从类型列表中删除受约束的类型来限制排列。然后,您可以将类型重新插入到约束定义的每个排列中。以下示例脚本将返回带有约束的排列:“ids 1 和 2 必须始终为所有组合的类型 a”。随意删除打印语句。

    from itertools import permutations
    
    # these define which types must be located at the given id (index + 1)
    constraints = [
        {'id': 1, 'type': "a"},
        {'id': 2, 'type': "a"}
    ]
    
    # this is the list of types to permute
    typeset = [
        {'id': 1, 'type': "a"},
        {'id': 2, 'type': "a"},
        {'id': 3, 'type': "b"},
        {'id': 4, 'type': "b"},
        {'id': 5, 'type': "a"}
    ]
    
    # we create lists of types to permute and remove the ones that are constrained
    types_to_permute = [d["type"] for d in typeset]
    constraint_types = [d["type"] for d in constraints]
    for constraint_type in constraint_types:
        types_to_permute.remove(constraint_type)
    print(types_to_permute)
    
    # we calculate the permutations for the unconstrained types
    permutations = list(permutations(types_to_permute, r=None))
    permutations = [list(permutation) for permutation in permutations]
    print(permutations)
    
    # we insert the constrained types in their given locations
    for permutation in permutations:
        for constraint in constraints:
            permutation.insert(constraint["id"] - 1, constraint["type"])
    print(permutations)
    
    # we reconstruct the permutations in the orignal format (list of dictionaries)
    final_permutations = []
    for permutation in permutations:
        final_permutation = []
        for index, type_object in enumerate(permutation):
            final_permutation.append({"id": index + 1, "type": type_object})
        final_permutations.append(final_permutation)
    print(final_permutations)
    

    最终的排列是:

    [
        [
            {'id': 1, 'type': 'a'},
            {'id': 2, 'type': 'a'},
            {'id': 3, 'type': 'b'},
            {'id': 4, 'type': 'b'},
            {'id': 5, 'type': 'a'}],
        [
            {'id': 1, 'type': 'a'},
            {'id': 2, 'type': 'a'},
            {'id': 3, 'type': 'b'},
            {'id': 4, 'type': 'a'},
            {'id': 5, 'type': 'b'}],
        [
            {'id': 1, 'type': 'a'},
            {'id': 2, 'type': 'a'},
            {'id': 3, 'type': 'b'},
            {'id': 4, 'type': 'b'},
            {'id': 5, 'type': 'a'}],
        [
            {'id': 1, 'type': 'a'},
            {'id': 2, 'type': 'a'},
            {'id': 3, 'type': 'b'},
            {'id': 4, 'type': 'a'},
            {'id': 5, 'type': 'b'}],
        [
            {'id': 1, 'type': 'a'},
            {'id': 2, 'type': 'a'},
            {'id': 3, 'type': 'a'},
            {'id': 4, 'type': 'b'},
            {'id': 5, 'type': 'b'}],
        [
            {'id': 1, 'type': 'a'},
            {'id': 2, 'type': 'a'},
            {'id': 3, 'type': 'a'},
            {'id': 4, 'type': 'b'},
            {'id': 5, 'type': 'b'}]]
    

    【讨论】:

    • 非常感谢!!这非常有帮助,并帮助我继续我的项目!只有一个后续问题:如果“类型”键位于嵌套字典中,我如何访问它。即,如果 typeset = { nest1 [ {'id': 1, 'type': "a"}, {'id': 2, 'type': "a"}, {'id': 3, 'type ': "b"}, {'id': 4, 'type': "b"}, {'id': 5, 'type': "a"} ] 嵌套 2 [ {此处为任意字典} ] }
    猜你喜欢
    • 1970-01-01
    • 2019-08-28
    • 2011-02-03
    • 2013-03-05
    • 2018-04-30
    • 1970-01-01
    • 2018-07-10
    • 2020-03-03
    • 2019-09-14
    相关资源
    最近更新 更多