小编Sar*_*ara的帖子

Python:如何在不重复元组内容的情况下生成元组列表的所有组合

我正在做一些谜语:

给定一个带有元组元组的字典:dictionary = {(p,q):n},我需要生成每个组合的新字典列表,这样在新字典中p和q都不会重复.并且在生成该词典列表期间或之后,基于使用字典值的计算,选择一个词典作为期望词典.

我的意思的例子(但更小):

dictionary = {(1,1): 1.0, (1,2): 2.0, (1,3): 2.5, (1,4): 5.0, (2,1): 3.5, (2,2): 6.0, (2,3): 4.0, (2,4): 1.0}

listofdictionaries = [{(1,1): 1.0, (2,2): 6.0}, {(1,1): 1.0, (2,3): 4.0}, (1,1): 1.0, (2,4): 1.0}, {(1,2): 2.0, (2,1): 3.5}, {(1,2): 2.0, (2,3): 4.0}, 等等

像这样的字典{(1,1): 1.0, (2,1): 3.5}是不允许的,因为q重复.

现在我的啜泣故事:我对编码很陌生......但我一直在尝试编写这个脚本来分析我的一些数据.但我也认为这是一个有趣的算法谜语.我写的东西适用于非常小的字典,但是当我输入一个大字典时,运行时间太长(下面复制).在我的脚本尝试中,我实际上生成了一个元组组合的列表,而不是我用来在脚本中引用我的主字典.我将在下面复制:

使用两个列表生成字典元组密钥:"ExpList1"和"ExpList2"

#first, I generate all the tuple combinations from my ExpDict dictionary
combos =(itertools.combinations(ExpDict,min(len(ExpList1),len(ExpList2))))

#then I generate a list of only the combinations that …
Run Code Online (Sandbox Code Playgroud)

python combinations python-itertools python-2.7 python-3.x

9
推荐指数
1
解决办法
1397
查看次数