For循环只在python中进行一次迭代

时间:2014-10-19 08:22:00

标签: python nested-loops

stat_to_grid_dist = []
for a in xrange(99):
    stat_to_grid_dist_colm = []
    for k in xrange(22):
        stat_to_grid_dist_row = []
        for l in xrange(28):
            stat_to_grid_dist_row.append(math.sqrt(
                math.pow(x_station[a]-xpt_grid[k],2) +
                math.pow(y_station[a]-ypt_grid[l],2)
            ))
        stat_to_grid_dist_colm.append(stat_to_grid_dist_row)
    stat_to_grid_dist.append(stat_to_grid_dist_colm)

使用上述内容时,第一个for循环(a for循环)仅在循环中移动一次。我可以访问stat_to_grid_dist的{​​{1}}列表中的任何内容,当我为循环中的任何位置放置一个print语句时,它只输出零。我似乎无法弄清楚发生了什么。我是否错误地了解了如何附加到列表列表中?

1 个答案:

答案 0 :(得分:0)

这将打印出99次。我对你的数据一无所知:

import math

x_station = range(1,100)
y_station = range(1,100)
xpt_grid = range(1,23)
ypt_grid = range(1,29)

stat_to_grid_dist = []
for a in xrange(99):
    stat_to_grid_dist_colm = []
    for k in xrange(22):
        stat_to_grid_dist_row = []
        for l in xrange(28):
            stat_to_grid_dist_row.append(
            math.sqrt(math.pow(x_station[a]-xpt_grid[k],2) + 
            math.pow(y_station[a]-ypt_grid[l],2)))
        stat_to_grid_dist_colm.append(stat_to_grid_dist_row)
    stat_to_grid_dist.append(stat_to_grid_dist_colm)
    print a