【问题标题】:Python create permutation from list without duplicatesPython从没有重复的列表中创建排列
【发布时间】:2021-03-11 09:22:26
【问题描述】:
#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 中尝试了排列,但它返回了所有匹配项。

【问题讨论】:

标签: python python-3.x list combinations permutation


【解决方案1】:

您必须使用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')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多