【问题标题】:How can I let my list return the list within a specific range如何让我的列表返回特定范围内的列表
【发布时间】:2021-12-25 20:59:47
【问题描述】:

所以我试图将列表board 中的每个“1”移动到列表的底部。这就是我的意思, 如果我在此输入,

board = [[" "," ","1"," "],
         [" "," ","1"," "],
         ["1","1"," "," "],
         ["1"," "," ","1"]]

我的输出应该返回

[[" "," "," "," "],
 [" "," "," "," "],
 ["1"," ","1"," "],
 ["1","1","1","1"]] 

如果你不明白,我基本上必须将列表中的每个“1”移动到 python 中板的最低列表。

这是我目前所拥有的,

board = [[" "," ","1"," "],
         [" "," ","1"," "],
         ["1","1"," "," "],
         ["1"," "," ","1"]]
def summ(board: [list[str]]):
    j = []
    for x in board:
        for i in x:
            j.append(i.count('1'))
    return sum(j)
def remove(board):
    r = []
    for x in board:
        for i in x:
            r.append(i.removesuffix('1'))
    return r
def new(board):
    s = list('1'* summ(board))
    return [remove(board) + s]
print(new(board))

我得到的输出是这样的

[[' ', ' ', '', ' ', ' ', ' ', '', ' ', '', '', ' ', ' ', '', ' ', ' ', '', '1', '1', '1', '1', '1', '1']]

我应该改变什么??

【问题讨论】:

  • list(zip(*(sorted(column) for column in zip(*board))))

标签: python list reference


【解决方案1】:

这很简单。只需转置数组,对其进行排序并再次转置。

board = [[" "," ","1"," "],
         [" "," ","1"," "],
         ["1","1"," "," "],
         ["1"," "," ","1"]]
boardT=list((map(list, zip(*board))))
boardS=[sorted(L) for L in boardT]
boardR=list((map(list, zip(*boardS))))
print(boardR)

#ans=[[' ', ' ', ' ', ' '],
     [' ', ' ', ' ', ' '],
     ['1', ' ', '1', ' '],
     ['1', '1', '1', '1']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2018-03-31
    • 2021-09-14
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多