如何计算python列表中的可能性

3 python

给出这样的列表:

num = [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

有10个三元素组合:

[123, 124, 125, 134, 135, 145, 234, 235, 245, 345]
Run Code Online (Sandbox Code Playgroud)

我该如何生成此列表?

小智 10

使用itertools.combinations:

import itertools

num = [1, 2, 3, 4, 5]
combinations = []
for combination in itertools.combinations(num, 3):
    combinations.append(int("".join(str(i) for i in combination)))
# => [123, 124, 125, 134, 135, 145, 234, 235, 245, 345]
print len(combinations)
# => 10
Run Code Online (Sandbox Code Playgroud)

编辑

如果您只对组合数感兴趣,可以跳过int(),join()和str().itertools.combinations()为您提供可能足够好的元组.

  • 如果OP只想知道组合的数量,那么实际生成所有组合并不是最有效的方法.</轻描淡写> (2认同)

Ste*_*202 5

你在谈论组合.有n!/(k!*(n - k)!)方法从n个元素的列表中取k 元素.所以:

>>> num = [1, 2, 3, 4, 5]
>>> fac = lambda n: 1 if n < 2 else n * fac(n - 1)
>>> combos = lambda n, k: fac(n) / fac(k) / fac(n - k)
>>> combos(len(num), 3)
10
Run Code Online (Sandbox Code Playgroud)

仅当您确实要生成所有组合时才使用itertools.combinations.如果您只是想知道不同组合的数量,那就不是了.

此外,与使用上面显示的代码相比,有更有效的方法来计算组合数.例如,

>>> from operator import truediv, mul
>>> from itertools import starmap
>>> from functools import reduce
>>> combos = lambda n, k: reduce(mul, starmap(truediv, zip(range(n, n - k, -1), range(k, 0, -1))))
>>> combos(len(num), 3)
10.0
Run Code Online (Sandbox Code Playgroud)

(注意,此代码使用浮点除法!)