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

Python缩进错误求助:unindent不匹配外部缩进层级

解决Python缩进错误及代码逻辑问题

我来帮你搞定这个头疼的缩进问题!你遇到的IndentationError: unindent does not match any outer indentation level,绝大多数情况都是代码里混合使用了空格和制表符作为缩进导致的——Python对缩进的一致性要求极其严格,哪怕一行用了制表符、另一行用了空格,就会让它识别缩进层次时混乱。

问题根源分析

你提供的代码里,大概率是部分行用了制表符(Tab键),部分行用了空格(Space键),在线格式化工具有时候处理这种混合缩进的情况会失效,尤其是工具默认的制表符转空格的设置和你的代码不匹配时。另外我还发现代码里有个小逻辑错误:判断2月的条件写错了,你写的if(date[2]==2),但date是按日/月/年分割的,date[2]是年份,应该改成date[1]==2才对。还有sum是Python的内置函数,最好别用来当变量名,避免覆盖内置功能。

修复后的完整代码

下面是统一用4个空格缩进、修正了逻辑错误、替换了变量名的代码:

import pandas  # 补全缺失的pandas导入,否则运行会报错

total_sum = 0.0
prev_month = None
year = ["2023"]  # 假设year变量为该值,需确保实际代码中已正确定义
new_date = []
no2_data = []

for i in range(0, len(no2)):
    date = no2.Date[i].split('/')
    for k in range(0, len(date)):
        t = int(date[k])
        date[k] = t
    if prev_month != date[1]:
        total_sum = 0.0
        print(type(total_sum))
        last_j = 1
        prev_month = date[1]
    # print(year[0])
    # print(date[2])
    if date[2] == int(year[0]):  # 统一类型后再比较,避免字符串与整数不匹配
        print(date[2])
        if date[1] in [1, 3, 5, 7, 8, 10, 12]:
            # print(date[1])
            for j in range(last_j, 32):  # range左闭右开,写32才能包含31号
                print(date[0], j)
                if date[0] == j:
                    # print(j)
                    new_date.append(no2.Date[i])
                    if no2.Concentration[i] == "":
                        no2_data.append(total_sum / (j - 1))  # 加括号修正运算顺序
                    else:
                        no2_data.append(no2.Concentration[i])
                    total_sum += float(no2_data[j - 1])
                    last_j = j + 1
                    break
                if date[0] > j:
                    new_date.append(f"{j}/{date[1]}/{date[2]}")  # 用f-string简化字符串拼接
                    no2_data.append(total_sum / (j - 1))
                    total_sum += float(no2_data[j - 1])
                    last_j = j
        elif date[1] in [4, 6, 9, 11]:
            for j in range(last_j, 31):  # 写31才能包含30号
                print(date[0], j)
                if date[0] == j:
                    # print(j)
                    new_date.append(no2.Date[i])
                    if no2.Concentration[i] == "":
                        no2_data.append(total_sum / (j - 1))
                    else:
                        no2_data.append(no2.Concentration[i])
                    total_sum += float(no2_data[j - 1])
                    last_j = j + 1
                    break
                if date[0] > j:
                    new_date.append(f"{j}/{date[1]}/{date[2]}")
                    no2_data.append(total_sum / (j - 1))
                    total_sum += float(no2_data[j - 1])
                    last_j = j
        elif date[1] == 2:  # 修正判断2月的条件,date[1]才是月份
            for j in range(last_j, 29):  # 写29才能包含28号
                if date[0] == j:
                    new_date.append(no2.Date[i])
                    if no2.Concentration[i] == "":
                        no2_data.append(total_sum / (j - 1))
                    else:
                        no2_data.append(no2.Concentration[i])
                    total_sum += float(no2_data[j - 1])
                    last_j = j + 1
                    break
                if date[0] > j:
                    new_date.append(f"{j}/{date[1]}/{date[2]}")
                    no2_data.append(total_sum / (j - 1))
                    total_sum += float(no2_data[j - 1])
                    last_j = j

# print(new_date)
# print(no2_data)
df = pandas.DataFrame({"date": new_date, "no2": no2_data})
df.to_csv("/Users/hareini/Downloads/output.csv", index=False)

额外修复的细节

  1. 统一缩进:所有缩进都用4个空格,彻底替换掉制表符;
  2. 修正逻辑错误:把判断2月的条件从date[2]==2改为date[1]==2;
  3. 修复range范围:Python的range是左闭右开的,比如range(last_j,31)只会到30,所以调整范围确保包含当月最后一天;
  4. 运算顺序修正:把sum/j-1改成total_sum/(j-1),避免先算除法再减1的错误;
  5. 变量名优化:把sum改成total_sum,避免覆盖Python内置的sum()函数;
  6. 字符串格式化优化:用f-string替代拼接,更简洁易读;
  7. 类型匹配修正:把date[2]==year[0]改成date[2]==int(year[0]),避免字符串和整数比较的潜在问题;
  8. 补全缺失导入:原代码没导入pandas,这里补上,不然运行会报错。

后续避免缩进问题的建议

在你的代码编辑器里设置:

  • 把制表符(Tab)自动转换成4个空格;
  • 开启缩进线显示,这样能直观看到每一行的缩进层次。

这样以后写代码就不会再遇到这类缩进错误啦!

内容的提问来源于stack exchange,提问作者Hareini Sreethi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:48:29