Python中二维列表如何获取子区域元素的组成
作者:瓜园耕读 时间:2021-02-16 02:41:01
用过NumPY
的应该都知道,在二维数组中可以方便地使用区域切片功能,如下图:
而这个功能在Python标准库的List
中是不支持的,在List
中只能以一维方式来进行切片操作:
但有时候我只想用一下这个功能,但又不想引入NumPY
。其实这时候我也是可以在Python中实现的。这时候,只需在一个类中实现__getitem__
特殊方法:
class Array:
"""实现__getitem__,支持序列获取元素、Slice等特性"""
def __init__(self, lst):
self.__coll = lst
def __repr__(self):
"""显示列表"""
return '{!r}'.format(self.__coll)
def __getitem__(self, key):
"""获取元素"""
slice1, slice2 = key
row1 = slice1.start
row2 = slice1.stop
col1 = slice2.start
col2 = slice2.stop
return [self.__coll[r][col1:col2] for r in range(row1, row2)]
试试看:
a = Array([['a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h'],
['i', 'j', 'k', 'l'],
['m', 'n', 'o', 'p'],
['q', 'r', 's', 't'],
['u', 'v', 'w', 'x']])
print(a[1:5, 1:3])
官方文档对__getitem__
的解释:
简而言之,其主要用来获取self[key]
的值。
我在这里为了突出问题解决,只列出了关键代码,异常判断、边界检查、条件限制,甚至其他一些特殊方法如__setitem__
、 __delitem__
与__len__
等代码,需视实际情况添加。
当然,也有其他处理方式,如以下所示代码,但不同方法无疑给了我各种场景下的多种选项。
a = [['a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h'],
['i', 'j', 'k', 'l'],
['m', 'n', 'o', 'p'],
['q', 'r', 's', 't'],
['u', 'v', 'w', 'x']]
sl = lambda row1, row2, col1, col2, lst: \
[lst[r][col1:col2] for r in range(row1, row2)]
sl(1, 5, 1, 3, a)
来源:http://www.2gua.info/post/72
标签:python,二维列表,元素
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
细数JavaScript 一个等号,两个等号,三个等号的区别
2023-08-25 08:22:09
php设置编码格式的方法
2023-11-14 12:01:22
go Cobra命令行工具入门教程
2023-06-24 18:27:12
![](https://img.aspxhome.com/file/2023/6/81566_0s.jpg)
Python+matplotlib实现华丽的文本框演示代码
2021-07-19 08:19:51
![](https://img.aspxhome.com/file/2023/1/92531_0s.png)
Python urllib.request对象案例解析
2022-04-14 22:24:43
python实现套接字创建
2021-09-09 05:12:04
MySQL中XML数据的XPath支持
2009-12-15 21:57:00
Chrome调试折腾记之JS断点调试技巧
2023-07-07 16:35:08
![](https://img.aspxhome.com/file/2023/1/55901_0s.png)
Python调用SMTP服务自动发送Email的实现步骤
2023-02-23 14:17:30
![](https://img.aspxhome.com/file/2023/3/65143_0s.png)
支持多风格变换的ASP分页类
2007-10-13 18:48:00
Python中的 Set 与 dict
2022-04-09 20:20:33
用python做一个搜索引擎(Pylucene)的实例代码
2023-06-30 22:12:40
![](https://img.aspxhome.com/file/2023/9/67329_0s.png)
[翻译]标记语言和样式手册 Chapter 11 打印样式
2008-02-11 18:44:00
![](https://img.aspxhome.com/file/UploadPic/20082/11/2008211185712733s.jpg)
如何编写一个只在Web服务关闭时执行的程序?
2009-11-08 19:03:00
pytorch 优化器(optim)不同参数组,不同学习率设置的操作
2021-09-14 05:05:44
![](https://img.aspxhome.com/file/2023/8/95478_0s.png)
对用户进行电话访谈的一点感想
2009-12-28 13:05:00
![](https://img.aspxhome.com/file/UploadPic/20101/11/2009-11-25_01-10s.png)
python工具之清理 Markdown 中没有引用的图片
2022-02-14 11:44:39
![](https://img.aspxhome.com/file/2023/0/67300_0s.png)
基于Python实现一个简易的数据管理系统
2023-08-14 11:49:38
![](https://img.aspxhome.com/file/2023/4/92274_0s.png)
通过索引优化含ORDER BY的MySQL语句
2010-03-13 12:20:00
详解Python字符串原理与使用的深度总结
2021-09-17 17:31:14