Ann*_*Zen 5
您可以尝试binations_with_replacement()
内置模块中的方法,itertools
:
from itertools import binations_with_replacement
for a, b in binations_with_replacement(range(6), 2):
if (a ** 2 + b ** 2) < 12:
print(a, b)
输出:
0 0
0 1
0 2
0 3
1 1
1 2
1 3
2 2
该binations_with_replacement()
方法与该方法类似binations()
,不同之处在于该binations_with_replacement()
方法允许在同一组合中多次使用一个元素。
请注意,它不包括1 0
作为解决方案,因为0 1
结果中已经存在。如果要包含此类,可以使用以下product()
方法:
from itertools import product
for a, b in product(range(6), repeat=2):
if (a ** 2 + b ** 2) < 12:
print(a, b)
输出:
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
3 0
3 1
更多推荐
两个,迭代,列表中,产品
发布评论