python - 实现嵌套或多维 python 列表扩展切片
问题描述
我想实现一个多维列表切片。我把它称为part
Mathematica 的类似内置函数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)
?还是已经有一些关于这种通用切片的包处理?
解决方案
这是我能得到的最接近的。子类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
参数并将其扩展为切片对象的元组。
推荐阅读
- zeromq - ZeroMQ Gnuradio 接口
- codeigniter - 试图从日期中删除 1 个月
- python - 在 python 中创建网格等值。行进立方体
- java - Spring REST 调用响应类型对象,差异很小
- html - Xamarin 在标签中形成 HTML
- excel - 如果在字符串中,则为单词着色
- javascript - Fullcalendar 4.x - 如何为事件添加唯一 ID
- amazon-web-services - 我正在尝试通过 AWS lambda 调用批处理操作。我希望批处理将输出返回到我的 lambda
- azure - 无法在 Azure Functions Linux 消费计划上编辑 CORS
- node.js - 在节点js中使用全局变量