__getitem__ 在列表列表上带有切片

2024-02-29

我正在创建一个代表列表列表的类。 __getitem__ 让我头疼。一切进展顺利,直到我引入切片作为参数。

演示代码

# Python version 2.7.5

class NestedLists:
   _Cells = [['.', '.', '.', '.', '.'],
             ['.', '.', 'N', '.', '.'],
             ['.', 'C', 'A', 'T', '.'],
             ['.', '.', 'P', '.', '.'],
             ['.', '.', '.', '.', '.']]

   def __getitem__(self, index):
      if isinstance(index, int):
         return self._Cells[index]
      elif isinstance(index, slice):
         return self._Cells[index]
      else:
         raise TypeError, "Invalid argument type"

nested = NestedLists()

print "Expecting A"
print nested[2][2]

print "Expecting CAT"
print nested[2][1:4]

print "Expecting ..N.."
print "          .CAT."
print "          ..P.."
print nested[1:4]

print "Expecting .N."
print "          CAT"
print "          .P."
print nested[1:4][1:4]

输出如下

Expecting A
A
Expecting CAT
['C', 'A', 'T']
Expecting ..N..
          .CAT.
          ..P..
[['.', '.', 'N', '.', '.'], ['.', 'C', 'A', 'T', '.'], ['.', '.', 'P', '.', '.']]
Expecting .N.
          CAT
          .P.
[['.', 'C', 'A', 'T', '.'], ['.', '.', 'P', '.', '.']]

显然,发生的情况是第二个 [] 运算符调用被应用于第一个运算符的输出......但保留在最外层列表的上下文中。然而,解决方案却让我无法理解。


您可能想更改多维访问的语法obj[row][col]使用单个元组索引:obj[row, col]。这是格式numpy's ndarraytype 使用,它非常有用,因为它可以让您立即查看索引的所有维度。你可以写一个__getitem__这将允许在任何维度进行切片:

def __getitem__(self, index):
   row, col = index
   if isinstance(row, int) and isinstance(col, (int, slice)):
      return self._Cells[row][col]
   elif isinstance(row, slice) and isinstance(col, (int, slice)):
      return [r[col] for r in self._Cells[row]]
   else:
      raise TypeError, "Invalid argument type"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

__getitem__ 在列表列表上带有切片 的相关文章

随机推荐