简体   繁体   English

如何向下移动嵌套 python 列表中的所有元素?

[英]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.

相关问题 如何检查嵌套列表树的所有元素是否相同? - How do I check if all the elements of a nested list tree are identical? 如何将 python 数据框中一行中的所有元素移动一列? - How do I shift all elements in a row in a python dataframe over by one column? 如何在python中相同的元组列表中找到所有元素? - How do i find all the elements in a list of tuples that are same in python? 在 Python 中,如何将列表的所有元素添加到集合中? - In Python, how do I add all the elements of a list to a set? 如何删除包含列表中所有元素的嵌套列表? - How can I remove nested lists encompassing all of my elements within a list? 如何在Python中递归地将列表元素“向下”移动到另一个列表的对应元素? - How can I shift list elements “down” to corresponding elements of another list recursively in Python? 在 Python 的嵌套列表中搜索 || 如何匹配 1 索引嵌套列表和 2 索引嵌套列表 - Searching within Nested lists in Python || How do I match a 1-index nested list, with a 2-index nested list I want to count the elements of a python list that is within a dataframe, and for the output to be a column in the dataframe. 我怎么做? - I want to count the elements of a python list that is within a dataframe, and for the output to be a column in the dataframe. How do I do that? 如何移动此列表中的元素? - How to shift elements in this list? Python-如何确保嵌套列表中元素的所有长度都相同? - Python - How to ensure all lengths of elements in a nested list are the same?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM