Creating 2D coordinates map in Python

故事扮演 提交于 2019-11-30 09:01:10

Using itertools.product():

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

The first solution is elegant, but you could also use a generator expression instead of a list comprehension:

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

This might be more efficient, depending on what you're doing with the data, because it generates the values on the fly and doesn't store them anywhere.

This also produces a generator; in either case, you have to use list to convert the data to a 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)]

Note that if you're using Python 2, you should probably use xrange, but in Python 3, range is fine.

UPDATED: Added @F.J. answer in the benchmark

The first implementation is the most pythonic way, and seems to be the fastest, too. Using 1000 for each, width and height, I register execution-times of

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

@F.J 0.27s

So yeah, his answer is the best.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!