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

标签 python

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

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

[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)

关于python - 使用键从不同列表中选择实体的唯一组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35808284/

相关文章:

python - 在 celery 中保存组结果 : AttibuteError

jquery - 如何让 jQuery 和 Python 在 GAME 应用程序中来回发送数据

python - 错误 1452 'Cannot add or update a child row'

python - 使用Python xml.etree解析xml文件: empty results

python - 在Python中使用二维列表的逻辑索引

python - 如何为基于 docker 的 python3 lambda 函数配置入口点/cmd?

python - 在 python 中获取给定日期的一年前的日期?

python - 在 Python 中访问未绑定(bind)到变量的对象

python - Pandas : local vs global dataframe in functions

python - 在 pandas 中使用 .groupby() 时如何输出 groupby 变量?