在Python中创建2D坐标图

13 投票
3 回答
35330 浏览
提问于 2025-04-17 12:02

我不是在找解决方案,而是在寻找更好的解决办法,或者用其他方式来实现,比如使用其他类型的列表推导式之类的。

我需要生成一个包含两个整数的元组的列表,用来获取地图坐标,比如说 [(1, 1), (1, 2), ..., (x, y)]。

所以我有以下这些:

width, height = 10, 5

方案 1

coordinates = [(x, y) for x in xrange(width) for y in xrange(height)]

方案 2

coordinates = []
for x in xrange(width):
    for y in xrange(height):
        coordinates.append((x, y))

方案 3

coordinates = []
x, y = 0, 0
while x < width:
    while y < height:
        coordinates.append((x, y))
        y += 1
    x += 1

还有其他的解决方案吗? 我最喜欢第一个。

3 个回答

-1

更新:在基准测试中添加了@F.J.的答案

第一个实现方式是最符合Python风格的,而且看起来也是最快的。使用1000作为宽度和高度的值,我记录到的执行时间是:

  1. 0.35903096199s
  2. 0.461946964264s
  3. 0.625234127045s

@F.J的结果是0.27s

所以,他的答案是最好的。

6

第一个解决方案很优雅,但你也可以用生成器表达式来代替列表推导式:

((x, y) for x in range(width) for y in range(height))

根据你处理数据的方式,这种方法可能更高效,因为它是实时生成值,而不是把它们存储起来。

这也会生成一个生成器;无论哪种情况,你都需要用 list 来把数据转换成列表。

>>> list(itertools.product(range(5), range(5)))
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), 
 (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 0), 
 (3, 1), (3, 2), (3, 3), (3, 4), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]

需要注意的是,如果你在使用 Python 2,可能应该用 xrange,但在 Python 3 中,使用 range 就可以了。

17

使用 itertools.product()

from itertools import product
coordinates = list(product(xrange(width), xrange(height)))

撰写回答