在Python中创建二维坐标图
我不是在寻找解决方案,我正在寻找更好的解决方案,或者只是通过使用其他类型的列表理解或其他方式来寻找不同的方法。
我需要生成 2 个整数的元组列表来获取地图坐标,例如 [(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
还有其他解决方案吗? 我最喜欢第一个。
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)]
So I have the following:
width, height = 10, 5
Solution 1
coordinates = [(x, y) for x in xrange(width) for y in xrange(height)]
Solution 2
coordinates = []
for x in xrange(width):
for y in xrange(height):
coordinates.append((x, y))
Solution 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个解决方案很优雅,但您也可以使用生成器表达式而不是列表理解:
这可能更有效,具体取决于您对数据所做的操作,因为它会动态生成值并且不存储他们在任何地方。
这也产生了一个发电机;无论哪种情况,您都必须使用
list
将数据转换为列表。请注意,如果您使用的是 Python 2,则可能应该使用
xrange
,但在 Python 3 中,range
就可以了。The first solution is elegant, but you could also use a generator expression instead of a list comprehension:
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.Note that if you're using Python 2, you should probably use
xrange
, but in Python 3,range
is fine.更新:在基准测试中添加了@FJ答案
第一个实现是最Pythonic的方式,而且似乎也是最快的。
对每个宽度和高度使用
1000
,我注册的执行时间为0.35903096199s
0.461946964264s
0.625234127045s
@ FJ
0.27s
所以是的,他的答案是最好的。
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 of0.35903096199s
0.461946964264s
0.625234127045s
@F.J
0.27s
So yeah, his answer is the best.
使用
itertools.product()
:Using
itertools.product()
: