noodles
noodles

Reputation: 19

Need some explanation in python arrays

I am converting a python algorithm to c#, and I need some explanation. So I have this list of lists:

offsets2 = [[(0.1, 0.1), (0.5, 0.1), (0.9, 0.1), (1.1, 0.1)],
            [(0.1, 0.5), (0.5, 0.5), (0.9, 0.5), (1.1, 0.5)],
            [(0.1, 0.9), (0.5, 0.9), (0.9, 0.9), (1.1, 0.9)],
            [(0.1, 1.0), (0.5, 1.0), (0.9, 1.0), (1.1, 1.0)]]

and this:

for offset in offsets2:
    offset = [(int(x + lane.width * dx), 
               int(y + self.canvas.row_height * dy))
              for dx, dy in offset]

and I am wondering what dx and dy are? I am guessing it's delta x and delta y, but just want to make sure, and also ask how to get them in c#.

Upvotes: 0

Views: 103

Answers (3)

bikeshedder
bikeshedder

Reputation: 7487

The code uses a so called List Comprehension.

It roughly translates to:

for offset in offsets2:
    _tmp = []
    for dx, dy in offset:
        _tmp.append((int(x + lane.width * dx), 
                     int(y + self.canvas.row_height * dy))
    offset = _tmp

The offset contains 2-tuples and the expression for dx, dy in offset unpacks those while iterating over it. It is the same as writing:

for coord in offset:
    if len(coord) != 2:
        raise ValueError
    dx = coord[0]
    dy = coord[1]
    ...

Upvotes: 1

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

You can put print statement to find out what you want.

for offset in offsets2:
    print offset
    tmp = []
    for dx, dy in offset:# for each pair (dx,dy) of offset
        print dx, dy
        newCoords = (int(x + lane.width * dx), 
               int(y + self.canvas.row_height * dy))
        tmp.append(newCoords)
    offset = tmp[:]

>>> [(0.1, 0.1), (0.5, 0.1), (0.9, 0.1), (1.1, 0.1)]
>>> 0.1, 0.1
>>> 0.5, 0.1
>>> 0.9, 0.1
....
>>> [(0.1, 0.5), (0.5, 0.5), (0.9, 0.5), (1.1, 0.5)]
>>> 0.1, 0.5
>>> 0.5, 0.5
>>> 0.9, 0.5

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

dx and dy are just temp variables which are allocated to each set of values in the list. So in the first iteration, dx=0.1, dy=0.1, in the second, dx=0.5, dy=0.1, and so on.

Upvotes: 0

Related Questions