Python从列表中创建无重复项的排列


#Input
t = ['pid', 'sn', 'uuid', 'host_id']
# Expected output
[('pid'),('sn'),('uuid'),('host_id'),('pid','sn'),('pid','uuid'),('pid','host_id'),('sn','uuid'),('sn','host_id',('uid','host_id'))]

我想先提取单个值,然后提取不重复的组合。

例如,('pid','sn')('sn','pid')是相同的。我只想要一个值。我尝试在itertools中进行排列,但它返回所有匹配项。

您必须使用combinations而不是permutations:

import itertools
t = ['pid', 'sn', 'uuid', 'host_id']
result = []
for n in range(1, len(t)+1):
for res in itertools.combinations(t, n):
result.append(res)
result

输出:

[('pid',),
('sn',),
('uuid',),
('host_id',),
('pid', 'sn'),
('pid', 'uuid'),
('pid', 'host_id'),
('sn', 'uuid'),
('sn', 'host_id'),
('uuid', 'host_id'),
('pid', 'sn', 'uuid'),
('pid', 'sn', 'host_id'),
('pid', 'uuid', 'host_id'),
('sn', 'uuid', 'host_id'),
('pid', 'sn', 'uuid', 'host_id')]

最新更新