Python 从不重复的列表中创建排列
Python create permutation from list without duplicates
#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')]
#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')]