Re: Help doing it the "python way"



On 5/24/12 22:22 , Scott Siegler wrote:

I am an experienced programmer but a beginner to python. As such, I can figure out a way to code most algorithms using more "C" style syntax.

I am doing something now that I am sure is a more python way but i can't quite get it right. I was hoping someone might help.

So I have a list of grid coordinates (x, y). From that list, I want to create a new list that for each coordinate, I add the coordinate just above and just below (x,y+1) and (x,y-1)

right now I am using a for loop to go through all the coordinates and then separate append statements to add the top and bottom.

is there a way to do something like: [(x,y-1), (x,y+1) for zzz in coord_list] or something along those lines?

If you have lot's of numerical data you can use the NumPy module (http://numpy.scipy.org/), your problem would reduce to something like this (copied from an IPython shell, could be shorter)

Regards,
Jan Kuiken


In [1]: first_list = np.arange(0, 10).reshape((5,2))

In [2]: above = np.array([0,-1])

In [3]: below = np.array([0,+1])

In [4]: N,d = first_list.shape

In [5]: second_list = np.empty((N*2,d))

In [6]: second_list[0::2] = first_list + above

In [7]: second_list[1::2] = first_list + below

In [8]: second_list
Out[8]:
array([[ 0., 0.],
[ 0., 2.],
[ 2., 2.],
[ 2., 4.],
[ 4., 4.],
[ 4., 6.],
[ 6., 6.],
[ 6., 8.],
[ 8., 8.],
[ 8., 10.]])

In [9]: first_list
Out[9]:
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
.



Relevant Pages

  • Re: Guidos new method definition idea
    ...     def $method: ... I agree that the code looks worse, but also shorter to read and write, ... tennets in the Zen of Python that don't chime well with this approach. ... By beautiful we mean ...
    (comp.lang.python)
  • Re: [kde] opening external URLs in new tabs?
    ... I modified the script to use pipe it's a ... cleaner code and also a shorter one! ... #!/usr/bin/env python ...
    (KDE)
  • Re: Guidos new method definition idea
    ... Ruby uses @ and @@ for similar purposes. ... I agree that the code looks worse, but also shorter to read and write, ... But that is not the way Python is meant to work. ...
    (comp.lang.python)
  • Re: Specific question about readlines versus xreadlines
    ... Did you know that stris a Python function that returns the string ... it's not a good idea to redefine str in your code as it ... And you can make it shorter still: ...
    (comp.lang.python)
  • IPython on Windows dir problem
    ... If I run ipython shell from 4NT, ddir and similar commands work fine. ... Python version is 2.4.3 and IPython version is 0.6.15. ...
    (comp.lang.python)