简体   繁体   English

如何有效地找到二维平面中所有坐标的排列?

[英]How to efficiently find permutations of all coordinates in 2D plane?

I need to list all coordinates of a 2D plane, with x and y axis ranging from 0 to 1066. Most answers I found recommends creating a list beforehand of all value of x and y axis, but I don't think that is the most efficient, since there will be 1067^2 elements as the result.我需要列出 2D 平面的所有坐标,x 和 y 轴的范围从 0 到 1066。我发现的大多数答案都建议事先创建一个包含 x 和 y 轴所有值的列表,但我认为这不是最多的高效,因为结果将有 1067^2 个元素。 The list should look something like this:该列表应如下所示:

list = [(0,0), (0,1),...(0,1066), (1,0), (1,1),...,(1,1066),...,(1066,0),...,(1066,1066)] . list = [(0,0), (0,1),...(0,1066), (1,0), (1,1),...,(1,1066),...,(1066,0),...,(1066,1066)]

I was thinking of using permutations since order matters, but I am still figuring out the best method.由于顺序很重要,我正在考虑使用排列,但我仍在找出最好的方法。

You can create a generator that you can use to iterate over every single pair of coordinates, without creating a rather large list of values:您可以创建一个生成器,用于迭代每一对坐标,而无需创建相当大的值列表:

As a generator expression:作为生成器表达式:

sizex, sizey = 3, 3   # replace with your own values
g = ((x, y) for x in range(sizex) for y in range(sizey))
print(type(g))
for coord in g:
    print(coord)

output:输出:

<class 'generator'>
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)

A generator as a lambda function:作为 lambda 函数的生成器:

sizex, sizey = 3, 3   # replace with your own values
g = lambda sizex, sizey: ((x, y) for x in range(sizex) for y in range(sizey))
print(type(g))
for coord in g(sizex, sizey):
    print(coord)

out:出去:

<class 'function'>
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)

As a regular function:作为常规功能:

def g(sizex, sizey):
    for x in range(sizex):
        for y in range(sizey):
            yield(x, y)


sizex, sizey = 3, 3   # replace with your own values
print(type(g))
for coord in g(sizex, sizey):
    print(coord)

Use Cartesian product to create lazy loading使用笛卡尔积创建延迟加载

impot itertools
mx, my = 1066, 1066

for x, y in itertools.product(range(mx), range(my)):
    print(x, y)

0 0
0 1
0 2
.
.
.
1065 1063
1065 1064
1065 1065

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM