[英]How do I shift all the elements within a nested python list downward?
we have a 4x4 board containing empty values, and 1s我们有一个包含空值和 1 的 4x4 板
board = [
[" "," ","1"," "],
[" "," ","1"," "],
["1","1"," "," "],
["1"," "," ","1"]
]
now we want to the final result to look like this?现在我们想要最终的结果是这样的吗?
gravity(board) == [
[" "," "," "," "],
[" "," "," "," "],
["1"," ","1"," "],
["1","1","1","1"]
]
Idea: For each column, you run from the bottom to top.想法:对于每一列,您从下到上运行。 If you found an "1", then assign it to the bottom.
如果找到“1”,则将其分配到底部。
for j in range(len(board[0])):
cnt = len(board)-1
for i in range(len(board)-1, -1, -1):
if (board[i][j]=='1'):
board[i][j]=''
board[cnt][j]='1'
cnt -= 1
Result:结果:
[[' ' ' ' '' ' ']
[' ' ' ' '' ' ']
['1' '' '1' ' ']
['1' '1' '1' '1']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.