此循环的目标是,对于列表star
中的每个[int, int]
元素(由stars
形式的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)
我期望的是它会打印一个"主循环"然后是" sub loop" len(stars) - 1
次。 (-1因为曾经,内圈和外圈中的星是相同的,我想忽略它)
我得到的是:
main loop
main loop
sub loop
main loop
sub loop
sub loop
main loop
sub loop
sub loop
sub loop
等等,直到最后一个循环,当它打印预期数量的"子循环"线。
即每次,它都会循环通过另一颗星。
为什么会发生这种情况,每次我怎样才能遍历每一颗星?
编辑: 问题是,当子循环中的星号与外循环相同时,我使用break来停止循环,而不是使用continue。更改以继续修复此问题。
答案 0 :(得分:0)
break
语句将导致子循环中断并在遇到同一个星时恢复到主循环。你想要的是子循环跳过这个迭代。尝试使用continue
代替break
。