繁体   English   中英

Python中一组3个数字的所有可能组合

[英]All possible combination of 3 numbers in a set in Python

我想打印集合中 3 个数字的所有可能组合( 0 ... n-1 ),而这些组合中的每一个都是唯一的。 我通过以下代码获得变量n

n = raw_input("Please enter n: ")

但我坚持想出算法。 请问有什么帮助吗?

from itertools import combinations
list(combinations(range(n),3))

只要您使用的版本晚于 Python 2.6,这就会起作用

itertools是你的朋友,特别是permutations

演示:

from itertools import permutations 

for item in permutations(range(n), 3): 
    print item

这是假设您拥有 Python 2.6 或更新版本。

如果您想要所有可能的组合值重复且位置不同,则需要使用如下产品:

from itertools import product
t = range(n)
print set(product(set(t),repeat = 3))

例如,如果 n = 3,输出将是:

set([(0, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 1), (1, 0, 1), (0, 0, 0), (0, 1, 0), (1, 1, 1)])

希望这可以帮助

combos = []
for x in xrange(n):
    for y in xrange(n):
        for z in xrange(n):
             combos.append([x,y,z])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM