[英]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.