问题
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