问题描述
在我提出问题之前,我想让大家知道我是一名初级编码员,我感谢所有输入,因此在此先感谢您的帮助。
假设我有以下对象:
set: [
{'id': 1
'type': a
},{'id': 2
'type': a
},{'id': 3
'type': b
},{'id': 4
'type': b
},{'id': 5
'type': a
}
]
我如何使用 itertools.permutations
来计算(并最终复制)'type'
键的所有组合?即有一个集合,其中 ids 3 和 5 的类型为 b
,其余为 a
,其中 ids 2 和 5 的集合为 b
,其余为 a
,等等.
此外,是否可以在给定某些条件的情况下计算组合(例如,对于所有组合,id 1 和 2 必须始终键入 a
)?
先谢谢大家
解决方法
以 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,{'id': 3,'type': "b"},{'id': 4,{'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'},'type': 'b'},'type': 'a'}],[
{'id': 1,'type': 'b'}],'type': 'b'}]]
,
您可以使用列表推导式提取所有 "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 permutations
。 r
是完全可选的,但它可以让您计算长度为 r
而不是 len(types)
的排列。
或者,让我们考虑一下您想要排列 List[Dict]
的情况:
from itertools import permutations
typeset = [...] # as before
types = range(len(typeset))
combos = list(permutations(types,r=None))
您现在可以根据存储在 typeset
中的索引检索 combos
的所有排列。但是,根据您的 typeset
的大小,我不建议这样做,因为这会消耗相当多的内存。