首页 > 解决方案 > 实现嵌套或多维 python 列表扩展切片

问题描述

我想实现一个多维列表切片。我把它称为partMathematica 的类似内置函数Part

到目前为止,我得到的低于定义。

class slicee:
    def __getitem__(self, item):
        return item

def part(x,sliceList): 
    if len(sliceList)==1:
        return x[sliceList[0]]
    else:
        if type(sliceList[0])==slice:
            tmp=x[sliceList[0]]
        else:
            tmp=[x[sliceList[0]]]
        return [part(i,sliceList[1:]) for i in tmp]

现在我们使用这个part。定义一个嵌套列表(为了方便起见,我使用了所有数字,我知道 numpy 可以完美地对其进行切片。但它只是一个示例。)

     l=[[[8, 9, 5, 5], [2, 0, 3, 4], [1, 1, 6, 6], [3, 9, 9, 3]],
 [[3, 4, 0, 2], [3, 1, 0, 2], [8, 2, 9, 5], [3, 5, 6, 8]],
 [[3, 5, 7, 2], [7, 2, 3, 9], [2, 1, 5, 2], [7, 6, 2, 2]],
 [[3, 0, 8, 3], [3, 7, 8, 1], [9, 4, 7, 2], [2, 0, 5, 7]]]

part(l,slicee()[:,:,0])

[[8, 2, 1, 3], [3, 3, 8, 3], [3, 7, 2, 7], [3, 3, 9, 2]]

这很好,只是我不喜欢必须显式编写的界面slicee()

是否有可能使界面part变得part(l,[:,:,0])更好甚至更好part(l,:,:,0)?还是已经有一些关于这种通用切片的包处理?

标签: python

解决方案


这是我能得到的最接近的。子类list和覆盖__getitem__

class Foo(list):
    def __getitem__(self, item):
        b = list(self)
        for thing in item:
            b = b[thing]
        return b

a = [[[8, 9, 5, 5], [2, 0, 3, 4], [1, 1, 6, 6], [3, 9, 9, 3]],
     [[3, 4, 0, 2], [3, 1, 0, 2], [8, 2, 9, 5], [3, 5, 6, 8]],
     [[3, 5, 7, 2], [7, 2, 3, 9], [2, 1, 5, 2], [7, 6, 2, 2]],
     [[3, 0, 8, 3], [3, 7, 8, 1], [9, 4, 7, 2], [2, 0, 5, 7]]]

>>> a = Foo(a)
>>> a[:,:,1]
[[3, 4, 0, 2], [3, 1, 0, 2], [8, 2, 9, 5], [3, 5, 6, 8]]
>>> a[:,1,1]
[3, 1, 0, 2]
>>> a[1,1,1]
1
>>>

警告:未评估意外后果。这里有一对...

>>> a[1,]
[[3, 4, 0, 2], [3, 1, 0, 2], [8, 2, 9, 5], [3, 5, 6, 8]]

>>> a[1]
Traceback (most recent call last):
  File "<pyshell#458>", line 1, in <module>
    a[1]
  File "C:\pyProjects\tmp.py", line 34, in __getitem__
    for thing in item:
TypeError: 'int' object is not iterable

>>> a[1,1,1,1]
Traceback (most recent call last):
  File "<pyshell#457>", line 1, in <module>
    a[1,1,1,1]
  File "C:\pyProjects\tmp.py", line 35, in __getitem__
    b = b[thing]
TypeError: 'int' object is not subscriptable

为了实现为具有两个参数的函数 - part(thelist,theslice). 您需要解析theslice参数并将其扩展为切片对象的元组。


推荐阅读