微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

列表变量在If语句内更改为<class'NoneType'>,并且在If语句内不允许任何列表操作

如何解决列表变量在If语句内更改为<class'NoneType'>,并且在If语句内不允许任何列表操作

嗨,我正在尝试从一个文件夹中读取降水量文件,并计算一年的总降水量。使用os和pandas遍历子目录并读取文件。每个文件包含1年的数据。然后计算每年的总降水量。

我还试图获取总降水量为零的年份的清单。因此,我声明了一个空列表(zero_year = []),然后使用if条件将总降雨量为零的年份附加到该空列表中。

我的问题是,zero_year会在if语句内切换为“ nonetype”类,并且不允许我将零降水年份添加到zero_year列表中。

我认为我缺少一些非常基本的东西。 感谢我可以获得的任何帮助。

# Walk through all subfolders and files under the "Precipitation" directory
# 1st loop gets list of sub directory under precipitation
# 2nd loop is for files under the sub directory
import os
import pandas as pd
filepath = "Precipitation\\"

global zero_year
for sub_directory in os.listdir(filepath):
    sub_filepath = filepath + sub_directory
   
    zero_year = []
    print(type(zero_year))

    for filename in os.listdir(sub_filepath):
        full_filepath = (sub_filepath + "\\" + filename)
        current_year = filename[6:8] + filename[9:]
                        
        # Read Precipitation File
        precip_file = pd.read_csv(full_filepath,sep=" ",header=None,skipinitialspace=True,names=["Day","Precip (mm)"],index_col=False)
        
        # Remove the last row that has no data using drop
        precip_file.drop(precip_file.tail(1).index,inplace=True)

        # Convert all strings to no data ---- NaN
        precip_file = precip_file.apply(pd.to_numeric,errors="coerce")
        
        # Sum all precipitation value in file to get total precipitation value for a year
        yearly_total = precip_file["Precip (mm)"].sum(skipna=True)
          
        # List years where total precipitation is zero
        if yearly_total == 0:                     
            zero_year = zero_year.extend(current_year)
            print(type(zero_year))
            print(zero_year)

解决方法

list.extend()在原位扩展列表,因此它将修改现有列表,然后返回None,而不是创建新列表并返回。

如果您更改

zero_year = zero_year.extend(current_year)

zero_year.extend(current_year)

应该可以。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。