【问题标题】:Creating all the possible combinations inside an element of list在列表元素中创建所有可能的组合
【发布时间】:2017-10-05 09:02:11
【问题描述】:

我需要探索列表的每个排列。假设我有这个初始变量:

samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9]

一个示例输出是:

output = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 2, 4, 5, 6, 7, 8, 9], [1, 3, 4, 2, 5, 6, 7, 8, 9], [1, 3, 5, 3, 2, 6, 7, 8, 9]] .... and so on.

这就是我所做的:

import itertools
samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def combinations(iterable, r):

    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

list(combinations_with_replacement(samplelist, 9))

由于列表的长度为 9,因此 9 的阶乘为 362,880。我正在尝试获取列表中元素的所有这些组合

但我的输出不是我想要达到的。

【问题讨论】:

  • import itertools 但从不使用它,相反你似乎是从文档中复制大致等效的 Python 代码,为什么不使用该模块?
  • 我认为我需要导入itertools,因为我在这里找到了函数源代码:docs.python.org/2/library/itertools.html
  • 使用模块!喜欢for comb in itertools.combinations(samplelist, 9): print(comb)
  • 您也可以使用较少项目(如 3 或 4)的输入。这样您就可以确定它是否按预期工作。

标签: python-3.x list itertools


【解决方案1】:

itertools.permutations(samplelist) 返回 9!列表

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-18
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多