Some syntactic sugar proposals

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Dec 2 01:14:14 EST 2010


On Wed, 01 Dec 2010 15:18:32 -0800, Dmitry Groshev wrote:

> Here is a fresh example of what I meant by my first proposal. You need
> to build a matrix like this:
> 2 1 0 ...
> 1 2 1 ...
> 0 1 2 ...
> ...
> ... 1 2 1
> ... 0 1 2
> You could do this by one-liner:
> [[(2 - abs(x - y)) if it > 0 else 0 for x in xrange(8)] for y in
> xrange(8)]
> ...but in reality you should write something like this: [[(lambda t: t
> if t > 0 else 0)(2 - abs(x - y)) for x in xrange(8)] for y in xrange(8)]
> or this
> [[(2 - abs(x - y)) if (2 - abs(x - y)) > 0 else 0 for x in xrange(8)]
> for y in xrange(8)]
> or even this
> def foo(x, y):
>     if abs(x - y) == 0:
>         return 2
>     elif abs(x - y) == 1:
>         return 1
>     else:
>         return 0
> [[foo(x, y) for x in xrange(8)] for y in xrange(8)]


All those one-liners give me a headache. At least your "foo" solution is 
understandable.

But I'd do it like this:

>>> array = [[0]*8 for _ in range(8)]
>>> for i in range(8):
...     array[i][i] = 2
...     if i > 0: array[i][i-1] = 1
...     if i < 7: array[i][i+1] = 1
...
>>> pprint.pprint(array)
[[2, 1, 0, 0, 0, 0, 0, 0],
 [1, 2, 1, 0, 0, 0, 0, 0],
 [0, 1, 2, 1, 0, 0, 0, 0],
 [0, 0, 1, 2, 1, 0, 0, 0],
 [0, 0, 0, 1, 2, 1, 0, 0],
 [0, 0, 0, 0, 1, 2, 1, 0],
 [0, 0, 0, 0, 0, 1, 2, 1],
 [0, 0, 0, 0, 0, 0, 1, 2]]



When you stop trying to make everything a one-liner, it's amazing how 
readable you can make code :)



-- 
Steven



More information about the Python-list mailing list