给定整数n> = m,我想用元素集{1,...,n}构建长度为m的所有递增列表的列表。
例如,如果n = 4且m = 2,我要[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
。
用很少的几行Python代码就能做到这一点吗?
我想建立一个有效的功能
def listOfLists(n, m):
????
return ? # the list of all increasing lists of m elements in {1, 2, ..., n}
谢谢!
我认为这可能有效:
n=4
m=2
result=[]
for i in range(1,n):
for j in range(i+1,n+1):
result.append([i,j])
您可以使用itertools
:
from itertools import combinations
m = 2
n = 4
list(combinations(list(range(1, n+1)), m))
使用itertools的组合
In [29]: from itertools import combinations
In [30]: def get_list(n, m):
...: return [i for i in combinations(range(1, n+1), m)]
In [31]: get_list(4, 2)
Out[31]: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]