简体   繁体   English

没有numpy的多维列表的切片

[英]slicing of multi-dimensional list without numpy

trying slicing of 2D list having dimensions = (3 X 3), whch results in 4 sub lists of (2 X 2) [ without numpy and other possible libraries ]尝试对维度 = (3 X 3) 的二维列表进行切片,这会导致 (2 X 2) 的 4 个子列表 [没有 numpy 和其他可能的库]

lis = [[1,1,1],[2,2,2],[3,3,3]]
print(lis)

dex = list([])

for i in range(0,2):
    for j in range(0,2):
        dex.append( [ lis[i:i+2,j:j+2] ] )
#       print( lis[i:i+2,j:j+2] )

expected:预期的:

 [ [[1,1][2,2]], [[1,1][2,2]], [[2,2][3,3]], [[2,2][3,3]] ]

getting: TypeError: list indices must be integers or slices, not tuple获取:TypeError:列表索引必须是整数或切片,而不是元组

Just use list comprehension to get the same effect.只需使用列表推导即可获得相同的效果。 For a 3D list, you'd have another comprehension inside that.对于 3D 列表,您将对此有另一种理解。

Instead of [lis[i:i+2,j:j+2]]而不是[lis[i:i+2,j:j+2]]

Use [x[j:j+2] for x in lis[i:i+2]]使用[x[j:j+2] for x in lis[i:i+2]]

The output of that is [[[1, 1], [2, 2]], [[1, 1], [2, 2]], [[2, 2], [3, 3]], [[2, 2], [3, 3]]] output 是[[[1, 1], [2, 2]], [[1, 1], [2, 2]], [[2, 2], [3, 3]], [[2, 2], [3, 3]]]

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

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