简体   繁体   English

python:用两个嵌套循环迭代数组

[英]python: Iterating over array with two nested loops

The goal of this loop is, for each star element (composed of x and y coords in the form of [int, int] ) in the list stars , calculate the distance and angle to every other star此循环的目标是,对于列表stars中的每个star元素(由[int, int]形式的 x 和 y 坐标组成),计算与其他star的距离和角度

#list to store lists of distances
star_map = []

#go through each star to calculate distance from this star
for star in stars:

    print("main loop")

    sub_map = [] #list of distances from this star


    for sub_star in stars: 

        print("sub loop")

        #find distance
        dx = float(star[0]-sub_star[0])
        dy = float(star[1]-sub_star[1])

        #if distance is zero, break because it's the same star
        if(dx == 0 and dy == 0):
            break

        #otherwise get distance and angle    
        dist = np.sqrt(dx ** 2 + dy ** 2)
        theta = get_theta(dx, dy)

        #add it to a list of distances from this star
        sub_map.append((dist, theta))
        print("sub loop")

    #add the list of distances from this star to the main list    
    star_map.append(sub_map)

What I would expect is that it prints one "main loop" followed by "sub loop" len(stars) - 1 times.我期望的是它打印一个“主循环”,然后是“子循环” len(stars) - 1次。 (-1 because once, the star in the inner and outer loops is the same, and I want to ignore that) (-1 因为有一次,内循环和外循环中的星星是一样的,我想忽略它)

What happens is that I get this:发生的事情是我得到了这个:

main loop
main loop
sub loop
main loop
sub loop
sub loop
main loop
sub loop
sub loop
sub loop

etc, etc, until the last loop, when it prints the expected number of "sub loop" lines.等等,直到最后一个循环,当它打印预期数量的“子循环”行时。

ie each time, it loops through one more star.即每次,它循环通过一颗星。

Why is this happening, and how can I loop through every star, every time?为什么会发生这种情况,我如何每次都遍历每颗星星?

Edit: The problem was that instead of using continue, I used break to stop the loop when the star in the sub loop was the same as the outer loop.编辑:问题是,当子循环中的星号与外循环相同时,我没有使用 continue,而是使用 break 来停止循环。 Changing to continue fixed this.更改为继续解决了这个问题。

The break statement will cause the sub loop to break and revert back to the main loop when it encounters the same star. break语句将导致子循环在遇到相同的星星时中断并返回到主循环。 What you want is for the sub loop to skip this iteration.您想要的是让子循环跳过此迭代。 Try using continue instead of break .尝试使用continue而不是break

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

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