aem*_*mdy 12 python iterator coordinates
我不是在寻找解决方案,我正在寻找更好的解决方案,或者通过使用其他类型的列表理解或其他方式来寻找更好的解决方案.
我需要生成一个2个整数的元组列表来获取地图坐标,如[(1,1),(1,2),...,(x,y)]
所以我有以下内容:
width, height = 10, 5
Run Code Online (Sandbox Code Playgroud)
解决方案1
coordinates = [(x, y) for x in xrange(width) for y in xrange(height)]
Run Code Online (Sandbox Code Playgroud)
解决方案2
coordinates = []
for x in xrange(width):
for y in xrange(height):
coordinates.append((x, y))
Run Code Online (Sandbox Code Playgroud)
解决方案3
coordinates = []
x, y = 0, 0
while x < width:
while y < height:
coordinates.append((x, y))
y += 1
x += 1
Run Code Online (Sandbox Code Playgroud)
还有其他解决方案吗?我最喜欢第一个.
And*_*ark 15
from itertools import product
coordinates = list(product(xrange(width), xrange(height)))
Run Code Online (Sandbox Code Playgroud)
第一个解决方案很优雅,但是您也可以使用生成器表达式来代替列表理解:
((x, y) for x in range(width) for y in range(height))
Run Code Online (Sandbox Code Playgroud)
这可能会更有效,具体取决于您对数据的处理方式,因为它会即时生成值,并且不会将其存储在任何地方。
这也会产生一个发电机。无论哪种情况,都必须使用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)]
Run Code Online (Sandbox Code Playgroud)
请注意,如果您使用的是Python 2,则可能应该使用xrange,但在Python 3中range则可以。