源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python中二维列表如何获取子区域元素的组成

  • 时间:2022-09-07 17:45 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python中二维列表如何获取子区域元素的组成
用过[code]NumPY[/code]的应该都知道,在二维数组中可以方便地使用区域切片功能,如下图: [img]http://files.jb51.net/file_images/article/201701/2017119142208466.png?2017019142218[/img] 而这个功能在Python标准库的[code]List[/code]中是不支持的,在[code]List[/code]中只能以一维方式来进行切片操作: [img]http://files.jb51.net/file_images/article/201701/2017119142236391.png?2017019142245[/img] 但有时候我只想用一下这个功能,但又不想引入[code]NumPY[/code]。其实这时候我也是可以在Python中实现的。这时候,只需在一个类中实现[code]__getitem__[/code]特殊方法:
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)]
[b]试试看:[/b]
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])
[img]http://files.jb51.net/file_images/article/201701/2017119142331845.png?2017019142339[/img] 官方文档对[code]__getitem__[/code]的解释: [img]http://files.jb51.net/file_images/article/201701/2017119142353163.png?201701914242[/img] 简而言之,其主要用来获取[code]self[key][/code]的值。 我在这里为了突出问题解决,只列出了关键代码,异常判断、边界检查、条件限制,甚至其他一些特殊方法[code]如__setitem__[/code] 、 [code]__delitem__[/code]与[code]__len__[/code]等代码,需视实际情况添加。 当然,也有其他处理方式,如以下所示代码,但不同方法无疑给了我各种场景下的多种选项。
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)
[img]http://files.jb51.net/file_images/article/201701/2017119142500138.png?201701914258[/img] [b]总结[/b] 以上就是这篇文章的全部内容了,Python编程一个吸引我的地方就是,它就像是一座金矿,挖着挖着很可能就挖出些意想不到的乐趣出来。希望本文的内容对大家学习或者使用python能有一定的帮助,如果有疑问大家可以留言交流。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部