基本上我需要这样的行列表:
[0,0]
[1,0],[0,1]
[2,0],[1,1],[0,2]
[3,0],[2,1],[1,2],[0,3]
[4,0],[3,1],[2,2],[1,3],[0,4]
最多任意数量的元素,然后退回
[4,1],[3,2],[2,3],[1,4]
[4,2],[3,3],[2,4]
并[4,3],[3,4]
[4,4]
我只是想在一个大的列表列表中想要所有这些对,所以我可以按照它们在上面出现的顺序迭代它们以进行等距渲染。
输出看起来像这样
[[(0,0)],[(1,0),(0,1)],[(2,0),(1,1),(0,2)] ....]等
答案 0 :(得分:1)
目前尚不清楚您正在寻找什么样的概括,但IIUC有很多方法可以做到。一种是从前一个列表构建每个子列表(为每个子元素添加一个子元素并避免重复),但另一个是直接从算术中工作:
def sherwood(n):
N = 2*n+1
for i in range(N):
low, high = max(0, i-n), min(i, n)
w = list(range(low, high+1))
yield zip(w[::-1], w)
给了我
>>> out = list(sherwood(2))
>>> for x in out: print(x)
[(0, 0)]
[(1, 0), (0, 1)]
[(2, 0), (1, 1), (0, 2)]
[(2, 1), (1, 2)]
[(2, 2)]
>>> out = list(sherwood(4))
>>> for x in out: print(x)
[(0, 0)]
[(1, 0), (0, 1)]
[(2, 0), (1, 1), (0, 2)]
[(3, 0), (2, 1), (1, 2), (0, 3)]
[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)]
[(4, 1), (3, 2), (2, 3), (1, 4)]
[(4, 2), (3, 3), (2, 4)]
[(4, 3), (3, 4)]
[(4, 4)]
答案 1 :(得分:1)
def create_lists(max_num):
retlist = []
for i in range(max_num+1):
i_list = []
for j in range(i, -1, -1):
i_list.append((j, i-j))
retlist.append(i_list)
for i in range(1, max_num+1):
i_list = []
for j in range(i, max_num+1):
i_list.append((max_num+i-j, j))
retlist.append(i_list)
return retlist