0

我正在将 python 算法转换为 c#,我需要一些解释。所以我有这个列表列表:

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)]]

还有这个:

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

我想知道 dx 和 dy 是什么?我猜它是 delta x 和 delta y,但只是想确定一下,并询问如何在 c# 中获取它们。

4

3 回答 3

1

你可以把打印语句找出你想要的。

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
于 2013-03-04T09:52:32.457 回答
1

该代码使用所谓的List Comprehension.

它大致翻译为:

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

offset包含 2 个元组,表达式for dx, dy in offset在对其进行迭代时解包这些元组。和写法一样:

for coord in offset:
    if len(coord) != 2:
        raise ValueError
    dx = coord[0]
    dy = coord[1]
    ...
于 2013-03-04T09:56:15.470 回答
0

dx并且dy只是分配给列表中每组值的临时变量。所以在第一次迭代中,dx=0.1, dy=0.1,在第二次中,dx=0.5, dy=0.1,依此类推。

于 2013-03-04T09:52:19.253 回答