[英]More elegant way to create a list of 2D points in Python
I need to create a list of 2D points (x,y) in python. 我需要在python中创建2D点(x,y)的列表。 This will do it 这会做到的
l = []
for x in range (30,50,5):
for y in range (1,10,3):
l.append((x,y))
So: print l
will produce: 因此: print l
将产生:
[(30, 1), (30, 4), (30, 7), (35, 1), (35, 4), (35, 7), (40, 1), (40, 4), (40, 7), (45, 1), (45, 4), (45, 7)]
Is there a more elegant way of doing this? 有没有更优雅的方式做到这一点?
Use itertools.product
: 使用itertools.product
:
from itertools import product
l = list(product(range(30,50,5), range(1,10,3)))
It scales better and should be faster than a generator expression, list comprehension, or explicit loops. 它比生成器表达式,列表理解或显式循环更好地缩放并且应该更快。
l = [(x,y) for x in range(30,50,5) for y in range(1,10,3)]
You can use a generator expression : 您可以使用生成器表达式 :
>>> l = list((x, y) for x in range(30, 50, 5) for y in range(1, 10, 3))
>>> l
[(30, 1), (30, 4), (30, 7), (35, 1), (35, 4), (35, 7), (40, 1), (40, 4), (40, 7), (45, 1), (45, 4), (45, 7)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.