[英]python: Iterating over array with two nested loops
此循环的目标是,对于列表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)
我期望的是它打印一个“主循环”,然后是“子循环” len(stars) - 1
次。 (-1 因为有一次,内循环和外循环中的星星是一样的,我想忽略它)
发生的事情是我得到了这个:
main loop
main loop
sub loop
main loop
sub loop
sub loop
main loop
sub loop
sub loop
sub loop
等等,直到最后一个循环,当它打印预期数量的“子循环”行时。
即每次,它循环通过一颗星。
为什么会发生这种情况,我如何每次都遍历每颗星星?
编辑:问题是,当子循环中的星号与外循环相同时,我没有使用 continue,而是使用 break 来停止循环。 更改为继续解决了这个问题。
break
语句将导致子循环在遇到相同的星星时中断并返回到主循环。 您想要的是让子循环跳过此迭代。 尝试使用continue
而不是break
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.