这是我要写的:
groups[m][n] = groups[m - 1][n] or ++gid
这是我必须写的:
g = groups[m - 1][n]
if g:
groups[m,n] = g
else:
gid += 1
groups[m][n] = gid
是否仅因为缺少
++
运算符,而在Python中没有更紧凑的编写方式了?我正在研究的方法的一个更大的样本:
groups = [[0] * self.columns] * self.rows
gid = 0
for m in xrange(self.rows):
for n in xrange(self.columns):
stone = self[m, n]
if stone == self[m - 1, n]:
if groups[m - 1][n]:
groups[m][n] = groups[m - 1][n]
else:
gid += 1
groups[m][n] = gid
elif stone == self[m, n - 1]:
if groups[m][n - 1]:
groups[m][n] = groups[m][n - 1]
else:
gid += 1
groups[m][n] = gid
我认为当我必须像这样吹牛时,阅读起来要困难得多,而且我要对
m-1
进行两次评估...我不确定如何压缩它。这是我想出的:
我围绕
int
创建了一个包装器类:class Int(object):
def __init__(self, i):
self.i = i
def pre(self, a=1):
self.i += a
return Int(self.i)
def post(self, a=1):
cpy = Int(self.i)
self.i += a
return cpy
def __repr__(self):
return str(self.i)
def __nonzero__(self):
return self.i != 0
可以这样使用:
def group_stones(self):
groups = [[None for _ in xrange(self.cols)] for _ in xrange(self.rows)]
gid = Int(0)
for m in xrange(self.rows):
for n in xrange(self.cols):
stone = self[m, n]
if stone == self[m - 1, n]:
groups[m][n] = groups[m - 1][n] or gid.pre()
elif stone == self[m, n - 1]:
groups[m][n] = groups[m][n - 1] or gid.pre()
else:
groups[m][n] = gid.pre()
就像我会用其他语言一样。
最佳答案
gid = [0] # list - mutable object
def incremented(gid):
gid[0] += 1
return gid[0]
groups[m][n] = groups[m - 1][n] or incremented(gid)
您可以在Int类中添加一些“魔术”:
class C(object):
...
def __add__(self, other):
self.i += other
return self.__class__(self.i)
def __radd__(self, other):
cpy = self.__class__(self.i)
self.i += other
return cpy
>>> print Int(2) + 1 # pre
3
>>> i = Int(2)
>>> print 1 + i # post
2
>>> print i
3
关于python - 没有++运算符,如何更紧凑地编写此语句?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11280152/