例如,如果我有一个列表:
L = [3, 3]
我想打印: 每个索引的以下可用移动:
[[3, 0], [2, 0], [1, 0], [3, 1], [2, 1], [1, 1]]
任何想法?
我试过[[i for i in lst] for lst in list]
,但这没有用
答案 0 :(得分:1)
这就是你的想法
my_list = [3,3]
final_list = []
for i in range(0, my_list[0] + 1):
for j in range(my_list[0], 0, -1):
final_list.append([j, i])
print(final_list)
输出:
[[3, 0], [2, 0], [1, 0], [3, 1], [2, 1], [1, 1], [3, 2], [2, 2], [1, 2], [3, 3], [2, 3], [1, 3]]
它比您在问题中列出的结果更多,但它涵盖了所有组合
答案 1 :(得分:1)
>>>import itertools as it
>>> L
[3, 3]
>>> res = [[[i,j] for j in range(L[1])] for i in range(L[0],0,-1)]
>>> print [i for i in it.chain.from_iterable(res)]
[[3, 0], [3, 1], [3, 2], [2, 0], [2, 1], [2, 2], [1, 0], [1, 1], [1, 2]]
希望能回答你的问题!
答案 2 :(得分:1)
>>> L = [3, 3]
>>> [[m, i] for i, n in enumerate(L) for m in range(n, 0, -1)]
[[3, 0], [2, 0], [1, 0], [3, 1], [2, 1], [1, 1]]
答案 3 :(得分:0)
如果你想使用pythonic方式
data = [3,3]
print([[a,b] for a in range(data[0]+1) for b in range(data[1]+1)])
输出将是
[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]
修改强>
我看到你不想要一个' 0'在第一个元素中,所以只需使用range(1,data[0]+1)
data = [3,3]
print([[a,b] for a in range(1,data[0]+1) for b in range(data[1]+1)])
输出将是
[[1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]