【问题标题】:All possible permutations of a set of lists in PythonPython中一组列表的所有可能排列
【发布时间】:2011-02-20 15:29:49
【问题描述】:

在 Python 中,我有一个包含 n 个列表的列表,每个列表都有可变数量的元素。如何创建一个包含所有可能排列的列表:

例如

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

我想要

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

请注意,我事先并不知道 n。我认为 itertools.product 是正确的方法,但它需要我提前知道参数的数量

【问题讨论】:

  • 我不明白——你为什么不计算列表来找到 n?
  • 我能做到,对我有什么帮助?

标签: python list permutation


【解决方案1】:

您无需提前知道n 即可使用itertools.product

>>> import itertools
>>> s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]
>>> list(itertools.product(*s))
[('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')]

【讨论】:

  • 是的 - Python 中的参数列表非常方便。
  • (有关参数列表的更多信息:docs.python.org/tutorial/…
  • 太棒了。我错过了如何正确使用参数列表。
  • 一看,一击,一绝。这就是我喜欢 Python 的原因!
  • 口才。是的,Python 很漂亮。
【解决方案2】:

您可以使用多级列表理解来做到这一点:

>>> L1=['a','b','c']
>>> L2=['d']
>>> L3=['e','f']
>>> [[i,j,k] for i in L1 for j in L2 for k in L3]
[['a', 'd', 'e'], ['a', 'd', 'f'], ['b', 'd', 'e'], ['b', 'd', 'f'], ['c', 'd', 'e'], ['c', 'd', 'f']]

【讨论】:

  • 这需要你提前知道n的数量(n = 3在你的回答中):)
  • 谢谢,但我不知道提前列出的数量。我有相当于 [L1, L2, L3, ...]
  • 啊,好吧,我不清楚你所说的“提前知道参数的数量”是什么意思——我想你可能是指列表的长度
【解决方案3】:

itertools.product 适合我。

>>> l=[ [ 1, 2, 3], [4], [5, 6] ]
>>> list(itertools.product(*l))
[(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)]
>>> l=[ [ 1, 2, 3], [4], [5, 6],[7,8] ]
>>> list(itertools.product(*l))
[(1, 4, 5, 7), (1, 4, 5, 8), (1, 4, 6, 7), (1, 4, 6, 8), (2, 4, 5, 7), (2, 4, 5, 8), (2, 4, 6, 7), (2, 4, 6, 8), (3, 4, 5, 7), (3, 4, 5, 8), (3, 4, 6,
 7), (3, 4, 6, 8)]
>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多