首页 > 解决方案 > 在python的循环条件中添加列表时出错

问题描述

while dir_loop_water < water_lenth:

    ds_water = gdal.Open('path'+ dirlist_water[dir_loop_water] , gdal.GA_ReadOnly)
    numer_of_band_water = str(ds_water.RasterCount)
    if numer_of_band_water == '3':
        print('water condition matched')
        rb_water = ds_water.GetRasterBand(1)
        band1_water_tmp = rb_water.ReadAsArray()
        band1_water = band1_water_tmp.tolist()

        rb2_water = ds_water.GetRasterBand(2)
        band2_water_tmp = rb2_water.ReadAsArray()
        band2_water = band2_water_tmp.tolist()

        rb3_water = ds_water.GetRasterBand(3)
        band3_water_tmp = rb3_water.ReadAsArray()
        band3_water = band3_water_tmp.tolist()

        [cols_water,rows_water] = band1_water_tmp.shape
        loop_water_cols = 0

        while loop_water_cols < cols_water:

            loop_water_rows = 0

            while loop_water_rows < rows_water:


                dataset.append([band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0])

                loop_water_rows = loop_water_rows +1
            del dataset[0]
            with open('path/dataset.csv', 'a') as f:
                    writer = csv.writer(f)
                    writer.writerows(dataset)
                    f.close()
            dataset= [None]
            loop_water_cols = loop_water_cols +1
    dir_loop_water= dir_loop_water+1

使用上面的代码,我想将长度为 4 的列表添加到数据集。

但我打印数据集的值(打印(数据集 [数字])),它像这样打印。

[0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0]
[0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]

根据我对上述代码的看法,我添加了一个包含四个值的列表。

但是,结果是两个具有四个值的列表的组合。

我找不到列表将在哪里合并。

感谢您让我知道如何一次只添加一个包含 4 个值的列表。

标签: pythonlistloopswhile-loop

解决方案


您的 dataset.append() 方法将整个列表附加到您的列表中(制作列表列表)。

要将新列表的每个项目附加到数据集中(如果我理解正确的话)使用 += 像这样:

dataset += [band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0]

这将产生一个像这样的列表:

[0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0, 0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]

推荐阅读