More elegant way to create a list of 2D points in Python

那年仲夏 提交于 2019-12-08 06:30:06

问题


I need to create a list of 2D points (x,y) in python. 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:

[(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?


回答1:


Use 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.




回答2:


l = [(x,y) for x in range(30,50,5) for y in range(1,10,3)]



回答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)]


来源:https://stackoverflow.com/questions/9714210/more-elegant-way-to-create-a-list-of-2d-points-in-python

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