これが独自のクラスであり、文字列を渡そうとする場合のハックです。
[] 演算子をオーバーライドするには?
class Array(object):
def __init__(self, m, n):
"""Create junk demo array."""
self.m = m
self.n = n
row = list(range(self.n))
self.array = map(lambda x:row, range(self.m))
def __getitem__(self, index_string):
"""Implement slicing/indexing."""
row_index, _, col_index = index_string.partition(",")
if row_index == '' or row_index==":":
row_start = 0
row_stop = self.m
elif ':' in row_index:
row_start, _, row_stop = row_index.partition(":")
try:
row_start = int(row_start)
row_stop = int(row_stop)
except ValueError:
print "Bad Data"
else:
try:
row_start = int(row_index)
row_stop = int(row_index) + 1
except ValueError:
print "Bad Data"
if col_index == '' or col_index == ":":
col_start = 0
col_stop = self.n
elif ':' in col_index:
col_start, _, col_stop = col_index.partition(":")
try:
col_start = int(col_start)
col_stop = int(col_stop)
except ValueError:
print "Bad Data"
else:
try:
col_start = int(col_index)
col_stop = int(col_index) + 1
except ValueError:
print "Bad Data"
return map(lambda x: self.array[x][col_start:col_stop],
range(row_start, row_stop))
def __str__(self):
return str(self.array)
def __repr__(self):
return str(self.array)
array = Array(4, 5)
print array
out: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
array[",1:3"]
out: [[1, 2], [1, 2], [1, 2], [1, 2]]
array[":,1:3"]
out: [[1, 2], [1, 2], [1, 2], [1, 2]]