Skip to main content
 首页 » 编程设计

python之使用键从不同列表中选择实体的唯一组合

2025年05月04日16yxwkf

很抱歉,如果有人问这个问题,我可能没有必要的词汇来找到正确的问题。

如果我有一些像这样的等长列表(或元组):

[6, 4, 7] [gold, blue, red] [dog, cat, echidna] [hot, cold, rainy] 

还有一组键,它们是已知范围内的连续整数,等于唯一组合的数量(在本例中为 81)。

是否可以为每个键从每个列表中选择一项,从而保证组合是唯一的? (并从组合中获取 key )。

这样

0 可能产生(6、金、猫、热)

1 可能会屈服(cat、4、gold、rainy)

2 可能会产生(热、红、针鼹、7)

等...

知道 (hot, red, echidna, 7) 是由 2 产生的选择吗?

假设列表的长度和顺序已知且固定,则保证列表中的项目在每个列表中和所有列表中都是唯一的,并且每个列表都可以排序/排序

请您参考如下方法:

所有列表中的所有元素都是唯一的

如果输入值在不同的列表中都是唯一的,那么你就可以了。减少元素以减少输出

import itertools 
 
input = [[6, 4], ['gold', 'blue'], ['dog', 'cat'], ['hot', 'cold']]; 
output = list(itertools.product(*input)) 
print output 

所以 list[0] -> (6, 'gold', 'dog', 'hot')

输出

 [(6, 'gold', 'dog', 'hot'), (6, 'gold', 'dog', 'cold'), (6, 'gold', 'cat', 'hot'), (6, 'gold', 'cat', 'cold'),  
 (6, 'blue', 'dog', 'hot'), (6, 'blue', 'dog', 'cold'), (6, 'blue', 'cat', 'hot'), (6, 'blue', 'cat', 'cold'),  
 (4, 'gold', 'dog', 'hot'), (4, 'gold', 'dog', 'cold'), (4, 'gold', 'cat', 'hot'), (4, 'gold', 'cat', 'cold'),  
 (4, 'blue', 'dog', 'hot'), (4, 'blue', 'dog', 'cold'), (4, 'blue', 'cat', 'hot'), (4, 'blue', 'cat', 'cold')] 

并非所有列表中的所有元素都是唯一的

然后只需使用 itertools.groupby

import itertools 
 
input = [[1, 2], [1, 2], [1, 2], [1, 2]]; 
output = [k for k,_ in list(itertools.groupby(itertools.product(*input)))] 
print output 

输出

[[1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 2, 2], [1, 1, 1, 2], [1, 1, 2, 2], [1, 2, 2, 2],  
[1, 1, 1, 2], [1, 1, 2, 2], [1, 2, 2, 2], [1, 1, 2, 2], [1, 2, 2, 2], [2, 2, 2, 2]]    

性能

以你的例子 timeit with number=1000

0.00650215148926 (without group by) 
0.02952003479    (with group by) 
0.0323181152344  (algorithm from @GarrettR)