Help doing it the "python way"

Terry Reedy tjreedy at udel.edu
Thu May 24 23:27:59 EDT 2012


On 5/24/2012 4:53 PM, Duncan Booth wrote:
> Scott Siegler<scott.siegler at gmail.com> wrote:
>>> Hello,
>>>> 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.

Hi, welcome to Python. I came here from C also.
>> 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)

The Python way, especially the Python 3 way, is to not make the new 
sequence into a concrete list unless you actually need a list to append 
or sort or otherwise mutate. In many use cases, that is not necessary.
>> 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?

> def vertical_neighbours(coords):
> for x, y in coords:
> yield x, y-1
> yield x, y+1
>> new_coords = list(vertical_neighbours(coords))

-- 
Terry Jan Reedy


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /