【问题标题】:Find all possible combinations找出所有可能的组合
【发布时间】:2011-06-11 06:35:29
【问题描述】:

我之前问过这个问题,但是关于另一种编程语言。

假设我有几个词根、前缀和后缀。

roots = ["car insurance", "auto insurance"]
prefix = ["cheap", "budget"]
suffix = ["quote", "quotes"]

Python 中是否有一个简单的函数可以让我构造三个字符向量的所有可能组合。

所以我想要一个列表或其他数据结构,它返回每个字符串的所有可能组合的以下列表。

cheap car insurance quotes
cheap car insurance quotes
budget auto insurance quotes
budget insurance quotes
...

【问题讨论】:

标签: python list


【解决方案1】:

使用itertools.product():

for p, r, s in itertools.product(prefix, roots, suffix):
    print p, r, s

【讨论】:

    【解决方案2】:

    无需导入库,因为 Python 已经为此提供了内置语法。它不仅会打印,还会返回您要求的数据结构,并且您可以将字符串连接在一起以启动:

    combinations = [
        p + " " + t + " " + s
        for t in ts for p in prefix for s in suffix]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多