简体   繁体   English

在Python中创建2D坐标图

[英]Creating 2D coordinates map in Python

I'm not looking for solution, I'm looking for a better solution or just a different way to do this by using some other kind of list comprehension or something else. 我不是在寻找解决方案,我正在寻找更好的解决方案,或者通过使用其他类型的列表理解或其他方式来寻找更好的解决方案。

I need to generate a list of tuples of 2 integers to get map coordinates like [(1, 1), (1, 2), ..., (x, y)] 我需要生成一个2个整数的元组列表来获取地图坐标,如[(1,1),(1,2),...,(x,y)]

So I have the following: 所以我有以下内容:

width, height = 10, 5

Solution 1 解决方案1

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

Solution 2 解决方案2

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

Solution 3 解决方案3

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

Are there any other solutions? 还有其他解决方案吗? I like the 1st one most. 我最喜欢第一个。

Using itertools.product() : 使用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将数据转换为列表。

>>> 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. 请注意,如果您使用的是Python 2,则应该使用xrange ,但在Python 3中, range很好。

UPDATED: Added @FJ answer in the benchmark 更新:在基准测试中添加@FJ答案

The first implementation is the most pythonic way, and seems to be the fastest, too. 第一个实现是最pythonic的方式,似乎也是最快的。 Using 1000 for each, width and height, I register execution-times of 每个,宽度和高度使用1000 ,我注册执行时间

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

@FJ 0.27s @FJ 0.27s

So yeah, his answer is the best. 所以是的,他的答案是最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM