Itertools组合不可重复:rgb等价于rbg等 [英] Itertools Combinations No Repeats: Where rgb is equivelant to rbg etc

查看:65
本文介绍了Itertools组合不可重复:rgb等价于rbg等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用itertools.combinations返回唯一组合.我已经搜索了几个类似的问题,但是找不到答案.

I'm trying to use itertools.combinations to return unique combinations. I've searched through several similar questions but have not been able to find an answer.

一个例子:

>>> import itertools
>>> e = ['r','g','b','g']
>>> list(itertools.combinations(e,3))
[('r', 'g', 'b'), ('r', 'g', 'g'), ('r', 'b', 'g'), ('g', 'b', 'g')]

出于我的目的,(r,g,b)与(r,b,g)相同,因此我只想返回(rgb),(rgg)和(gbg).

For my purposes, (r,g,b) is identical to (r,b,g) and so I would want to return only (rgb),(rgg) and (gbg).

这只是一个说明性示例,我想忽略所有此类重复项".列表e最多可以包含5个元素.每个单独的元素可以是r,g或b.总是从e寻找3个元素的组合.

This is just an illustrative example and I would want to ignore all such 'duplicates'. The list e could contain up to 5 elements. Each individual element would be either r, g or b. Always looking for combinations of 3 elements from e.

具体来说,以下是我希望称为有效"的唯一组合:(rrr),(ggg),(bbb),(rgb).

To be concrete, the following are the only combinations I wish to call 'valid': (rrr), (ggg), (bbb), (rgb).

所以也许这个问题归结为如何将(rgb)的任何变化都等同于(rgb),因此将其忽略.

So perhaps the question boils down to how to treat any variation of (rgb) as equal to (rgb) and therefore ignore it.

我可以使用itertools实现这一目标,还是需要编写自己的代码以将重复项"放在此处?如果没有itertools解决方案,那么我可以轻松地检查每个变量是否都是(rgb)的变体,但这有点不合Python".

Can I use itertools to achieve this or do I need to write my own code to drop the 'dupliates' here? If no itertools solution then I can just easily check if each is a variation of (rgb), but this feels a bit 'un-pythonic'.

推荐答案

根据您对有效输出"的定义,您可以像这样直接构建它们:

According to your definition of "valid outputs", you can directly build them like this:

from collections import Counter

# Your distinct values
values = ['r', 'g', 'b']

e = ['r','g','b','g', 'g']

count = Counter(e)
# Counter({'g': 3, 'r': 1, 'b': 1})

# If x appears at least 3 times, 'xxx' is a valid combination  
combinations = [x*3 for x in values if count[x] >=3]

# If all values appear at least once, 'rgb' is a valid combination
if all([count[x]>=1 for x in values]):
    combinations.append('rgb')

print(combinations)
#['ggg', 'rgb']

这比创建所有可能的组合并随后过滤有效组合更为有效.

This will be more efficient than creating all possible combinations and filtering the valid ones afterwards.

这篇关于Itertools组合不可重复:rgb等价于rbg等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆