You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python技术问题:创建给定值列表及合并多数组最大值为单列表

我来帮你解决这两个问题:

1. 如何使用Python创建包含给定值的列表?

这里有几种实用的方法,你可以根据需求选择:

  • 直接字面量定义:最直观的方式,把目标值放在方括号里即可
    # 包含多种类型值的列表
    my_list = [10, "apple", False, 3.14]
    
  • 使用list()构造函数:可以把元组、字符串等可迭代对象转换成列表
    # 从元组生成列表
    num_list = list((2, 4, 6))
    # 从字符串拆分出字符列表
    char_list = list("hello")  # 结果为 ['h','e','l','l','o']
    
  • 列表推导式:适合按规则批量生成元素,比如生成有规律的数值序列
    # 生成1到20的奇数列表
    odd_list = [x for x in range(1,21) if x % 2 != 0]
    
  • 重复元素快速生成:如果需要多个相同元素,用乘法就能快速实现
    # 创建包含6个"test"的列表
    repeat_list = ["test"] * 6  # 结果为 ["test","test","test","test","test","test"]
    
2. 合并所有最大值到单个列表的解决方案

你的代码问题很明确:每次循环都会重新初始化列表L——也就是L=[]写在了for循环内部,导致每次循环都生成一个新的空列表,只能加入当前循环的最大值,最后输出的就是一个个独立的单元素列表。

解决方法非常简单:把L=[]移到for循环外面,让整个循环过程共用同一个列表,每次循环只往里面追加新的最大值即可。

修改后的完整代码如下:

import numpy as np
import re
import gdal
import ogr
from osgeo import gdal_array
from gdalconst import *
import os
import osr
import shutil
import h5py
import subprocess
import operator

#np.set_printoptions(threshold=np.inf)
indir = '/home/vigna/Documents/LST_29_03'
directory=os.fsencode(indir)
e=1
# 将列表初始化移到循环外部,确保全程使用同一个列表
L = []
for file in os.listdir(directory):
    file1=os.fsdecode(file)
    if '_Gadchiroli' in file1:
        b=str(e)+'_Gadchiroli.tif'
        #print(file1)
        gadchiroli=gdal.Open(b,GA_ReadOnly)
        gadchiroli_arry=gadchiroli.ReadAsArray()
        a=np.amax(gadchiroli_arry)
        # 往已有的列表中追加当前最大值
        L.append(a)
        e+=1
# 循环结束后再打印完整列表,而不是每次循环都打印
print(L)

修改后,所有的最大值都会被收集到同一个列表L中,最终打印出来的就是包含所有最大值的单列表(比如原来输出[150]、[162]、[148],现在会输出[150, 162, 148])。

内容的提问来源于stack exchange,提问作者vigna purohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:12:25