生成长度为n的元组的Pythonic方法
给定一个最小值和一个最大值,我想得到一个长度为n的元组,每个元素在最小值和最大值之间。例如,如果min是10,max是20,如果n是2,我想得到[(10,10),(10,11),…,(19,19)]。我只对数字的组合感兴趣,所以如果我已经有了(18,19),我就不需要(19,18) 我可以用长度为2的元组来解决这个问题,但我不太确定如何将它扩展到长度大于2的元组。我认为一种方法是将每个数字转换为字符串,然后调用其上的iterations.combines函数,然后将其转换回整数。但这似乎是不必要的复杂,想知道是否有一种更像蟒蛇的方式来做到这一点生成长度为n的元组的Pythonic方法,python,Python,给定一个最小值和一个最大值,我想得到一个长度为n的元组,每个元素在最小值和最大值之间。例如,如果min是10,max是20,如果n是2,我想得到[(10,10),(10,11),…,(19,19)]。我只对数字的组合感兴趣,所以如果我已经有了(18,19),我就不需要(19,18) 我可以用长度为2的元组来解决这个问题,但我不太确定如何将它扩展到长度大于2的元组。我认为一种方法是将每个数字转换为字符串,然后调用其上的iterations.combines函数,然后将其转换回整数。但这似乎是不必要
fangs = [(s, e) for s in range(min_fang, max_fang) for e in range(min_fang, max_fang) if e >= s]
您正在这里寻找:
带替换部件意味着允许在输出中的多个位置使用范围中的值,因此(10,10)
是有效的输出
演示:
您正在寻找带替换件的组合:
from itertools import combinations_with_replacement
list(combinations_with_replacement(range(min_fang, max_fang), n))
>>> from itertools import combinations_with_replacement
>>> min, max, n = 10, 20, 2
>>> for combo in combinations_with_replacement(range(min, max), n):
... print(combo)
...
(10, 10)
(10, 11)
(10, 12)
(10, 13)
(10, 14)
(10, 15)
(10, 16)
(10, 17)
(10, 18)
(10, 19)
(11, 11)
(11, 12)
(11, 13)
(11, 14)
(11, 15)
(11, 16)
(11, 17)
(11, 18)
(11, 19)
(12, 12)
(12, 13)
(12, 14)
(12, 15)
(12, 16)
(12, 17)
(12, 18)
(12, 19)
(13, 13)
(13, 14)
(13, 15)
(13, 16)
(13, 17)
(13, 18)
(13, 19)
(14, 14)
(14, 15)
(14, 16)
(14, 17)
(14, 18)
(14, 19)
(15, 15)
(15, 16)
(15, 17)
(15, 18)
(15, 19)
(16, 16)
(16, 17)
(16, 18)
(16, 19)
(17, 17)
(17, 18)
(17, 19)
(18, 18)
(18, 19)
(19, 19)
from itertools import combinations_with_replacement
list(combinations_with_replacement(range(min_fang, max_fang), n))