【问题标题】:How to apply itertools.product to a nested list in Python如何将 itertools.product 应用于 Python 中的嵌套列表
【发布时间】:2018-01-30 06:17:09
【问题描述】:

假设我有一个嵌套的字符串列表

lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]]

我想从嵌套列表生成所有可能的组合,如下所示:

new_lst = [['a', 'b', 'd'],
           ['a', 'b', 'e', 'f'],
           ['a', 'c', 'd'],
           ['a', 'c', 'e', 'f']]

我发现了一些可能与我的问题有关的问题。 how to produce a nested list from two lists in python 但是,我的问题是更复杂的问题。

【问题讨论】:

  • 我会展平列表,然后使用集合。 itertools 可能有一个自动执行此操作的方法。
  • @MidhunMohan 在那个问题中,他们正在从一个简单的列表中获取组合,而 OP 正在询问他的特定嵌套列表的产品
  • @JonKiparsky,我不相信你固定标题而是淡化了它。我相信正确的标题应该更像是“如何将 itertools.product 应用于 Python 中的嵌套列表”。

标签: python python-3.x list nested-lists


【解决方案1】:

这就是诀窍 -

import itertools
lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]]
outp = list(itertools.product(*lst))
out = []
for i in outp:
    temp = []
    for j in i:
        if isinstance(j, list):
            for k in j:
                temp.append(k)
        else:
            temp.append(j)
    out.append(temp)
print(out)

首先使用itertools.product 形成输出材料,然后简单地以嵌套列表被展平的方式对其进行格式化。

输出

[['a', 'b', 'd'], ['a', 'b', 'e', 'f'], ['a', 'c', 'd'], ['a', 'c', 'e', 'f']]

【讨论】:

  • 好答案。尽量避免print(here) 声明
  • 嗯奇怪为什么这被否决了,它是一个完美的解决方案。
  • @VikasDamodar 处理了它。谢谢!
  • @RoadRunner 想知道同样的 :-)
【解决方案2】:

类似于@VivekKalyanarangan,但具有适当的压扁器:

>>> def flatten(nl):
...     for e in nl:
...         if isinstance(e, str):
...             yield e
...             continue
...         try:
...             yield from flatten(e)
...         except TypeError:
...             yield e
... 

>>> lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]]
>>> 
>>> list(map(list, map(flatten, itertools.product(*lst))))
[['a', 'b', 'd'], ['a', 'b', 'e', 'f'], ['a', 'c', 'd'], ['a', 'c', 'e', 'f']]

【讨论】:

  • 如果我将数据更改为lst = [[1], [2, 3], [4, [5, 6]]],此解决方案仍然有效。那么isinstance(e, str) 真正为你做了什么?
【解决方案3】:

您可以使用chain.from_iterable() 来扁平化结果:

from itertools import product, chain

lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]]

[list(chain.from_iterable(i)) for i in product(*lst)]
# [['a', 'b', 'd'], ['a', 'b', 'e', 'f'], ['a', 'c', 'd'], ['a', 'c', 'e', 'f']]

【讨论】:

    【解决方案4】:

    使用列表理解的另一种方式

    >>> ls = [['a'], ['b', 'c'], ['d', ['e', 'f']]]
    >>> res = ['']
    >>> for elem in ls:
    ...     res = [list(j) + list(e) for j in res for e in elem]
    ... 
    >>> res
    [['a', 'b', 'd'], ['a', 'b', 'e', 'f'], ['a', 'c', 'd'], ['a', 'c', 'e', 'f']]
    

    【讨论】:

      【解决方案5】:

      这就是你要找的吗?

      from itertools import permutations
      lst = [['a'], ['b', 'c'], ['d', ['e', 'f']]]
      list(permutations(lst))
      

      否则,试试这个:

      lst = ['a','b','c','d','e','f']
      list(permutations(lst))   ##will return all possible combos
      

      【讨论】:

        猜你喜欢
        • 2011-03-03
        • 1970-01-01
        • 2021-11-03
        • 1970-01-01
        • 2018-10-18
        • 2021-07-12
        • 1970-01-01
        • 1970-01-01
        • 2021-04-26
        相关资源
        最近更新 更多