繁体   English   中英

Python 如何获取二维列表的所有矩形子集

[英]Python How to Get All Rectangular Subsets of a 2D list

假设给了我一个 2D 列表

001
111
111

我想获取二维列表的所有可能子集,它们是矩形并包含左上角元素/ grid[0][0]处的元素(我不知道如何描述它)

它应该是 output:

0

00

001

0
1

00
11

001
111

0
1
1

00
11
11

001
111
111

您将如何获得所有可能的子集? 我对如何实现它没有最模糊的想法。

根据您的解释,我想出了以下解决方案:

import numpy as np

list1=[[0,0,1],[1,1,1],[1,1,1]]

df=pd.DataFrame(list1, columns=['a','b','c'])

list2=[]



for i in range(1,4):
    for j in range(1,4):
        list2.append(df.iloc[:i,:j].to_numpy('int').tolist())

Output:

[[[0]], 
 [[0, 0]],
 [[0, 0, 1]],
 [[0], [1]],
 [[0, 0], [1, 1]],
 [[0, 0, 1], [1, 1, 1]],
 [[0], [1], [1]],
 [[0, 0], [1, 1], [1, 1]],
 [[0, 0, 1], [1, 1, 1], [1, 1, 1]]]

如果您希望拥有更高阶的矩阵,那么您只需将 4 更改为您希望for i/j in range(2,4)的数字。

一个简单的方法是:

for i in range(n):
    for j in range(n):
        x = grid[0:i+1]
        for k in x:
            print(k[0:j+1])
        print()
ints = [
    [0, 0, 1],
    [1, 1, 1],
    [1, 1, 1]
]

def get_slice(ints, x, y):
    rows = ints[0:y+1]
    return list(map(lambda row: row[0:x+1], rows))

for row in get_slice(ints, 2, 1):
    print(*row)

Output:

0 0 1
1 1 1

get_slice首先根据参数yints进行切片,这只会产生我们感兴趣的“行”。然后我们根据参数x对每一行进行切片。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM