【问题标题】:Generate combinations of a list of strings without repetitions and anchor element生成不重复的字符串列表和锚元素的组合
【发布时间】:2021-08-22 01:02:16
【问题描述】:

我有一个如下所示的列表:

x = [ 'foo', 'bar', 'alpha' ]

输出应该如下所示。所以'foo'需要始终出现在输出中

[
 ['foo'],
 ['foo', 'bar']
 ['foo','alpha']
 ['foo','bar','alpha']
]

我查看了 itertools.permutationsitertools.combinations 但两者似乎都不适用于此用例,因为它们认为值是唯一的按位置而不是数组中的值。

【问题讨论】:

  • 所以,单独处理foo。将其从最后一个中删除,然后对剩余的内容运行正常排列。
  • @Roberts itertools.permutations(['bar', 'alpha']) 给了我两个输出 ['bar', 'alpha'],['alpha','bar'] 但我也需要像 ['bar'] 和 ['alpha'] 这样的单个实例能够与 'foo' 组合。如何获得所有 4 个输出?

标签: python combinations permutation


【解决方案1】:

您可以在x[1:] 上使用combinations,改变参数r

import itertools

x = ['foo', 'bar', 'alpha']

output = []
for r in range(len(x)):
    output += [['foo'] + list(a) for a in itertools.combinations(x[1:], r)] # attach 'foo' to each item

print(output) # [['foo'], ['foo', 'bar'], ['foo', 'alpha'], ['foo', 'bar', 'alpha']]

在python 3.5+中,可以在循环中使用unpacking来增强可读性:

    output += [['foo', *a] for a in itertools.combinations(x[1:], r)]

【讨论】:

  • 使用itertools.combinations 的好方法。干得好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 2023-02-19
  • 1970-01-01
相关资源
最近更新 更多