更优雅的方式在Python中创建2D点列表

时间:2012-03-15 04:56:35

标签: python list 2d

我需要在python中创建一个2D点(x,y)列表。 这样做

l = []

for x in range (30,50,5):
    for y in range (1,10,3):
        l.append((x,y))

所以: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)]

有更优雅的方式吗?

3 个答案:

答案 0 :(得分:13)

使用itertools.product

from itertools import product
l = list(product(range(30,50,5), range(1,10,3)))

它可以更好地扩展,并且应该比生成器表达式,列表推导或显式循环更快。

答案 1 :(得分:8)

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

答案 2 :(得分:1)

您可以使用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)]