簡體   English   中英

不重復的列表的唯一排列

[英]Unique permutations of a list without repetition

我知道有很多關於排列唯一可變長度)的帖子,但我無法使用它們來解決我的特定問題。

假設我有一個美國大都市區列表: ['nyc','sf','atl']

我需要 output 2 個地鐵的排列而不重復。 例如,我嘗試過:

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

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

但是,請注意 NYC 和 ATL 配對了兩次: ('nyc', 'atl')('atl', 'nyc') 理想的 output 將是:

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

正如@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