简体   繁体   English

不重复的列表的唯一排列

[英]Unique permutations of a list without repetition

I understand there are many, many posts about permutations ( unique , variable length , etc .), but I have not been able to use them to solve my particular issue.我知道有很多关于排列唯一可变长度)的帖子,但我无法使用它们来解决我的特定问题。

Let's say I have a list of metropolitan areas in the United States: ['nyc','sf','atl']假设我有一个美国大都市区列表: ['nyc','sf','atl']

I need to output a permutation of 2 metros without repetition.我需要 output 2 个地铁的排列而不重复。 For example, I've tried:例如,我尝试过:

set(itertools.permutations(['nyc','sf','atl'], 2))

{('atl', 'nyc'),
 ('atl', 'sf'),
 ('nyc', 'atl'),
 ('nyc', 'sf'),
 ('sf', 'atl'),
 ('sf', 'nyc')}

However, notice that NYC and ATL are paired twice: ('nyc', 'atl') and ('atl', 'nyc') .但是,请注意 NYC 和 ATL 配对了两次: ('nyc', 'atl')('atl', 'nyc') The ideal output would be:理想的 output 将是:

{('nyc', 'nyc'),
 ('nyc', 'sf'),
 ('nyc', 'atl'),
 ('sf', 'sf'),
 ('sf', 'atl'),
 ('atl', 'atl')}

As mentioned by @Daniel Mesejo comment, use combinations.正如@Daniel Mesejo 评论所提到的,使用组合。

>>> import itertools
>>> set(itertools.combinations(['nyc','sf','atl'], 2))
{('nyc', 'atl'), ('sf', 'atl'), ('nyc', 'sf')}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM