简体   繁体   中英

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']

I need to output a permutation of 2 metros without repetition. 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') . The ideal output would be:

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

As mentioned by @Daniel Mesejo comment, use combinations.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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