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

运行Python代码时遇TypeError:'int' has no length问题求助

问题分析与解决

错误原因

你在最后一段代码里,遍历num列表的每个整数元素x,并把x传给sort函数,但sort函数的设计是接收列表作为参数(因为它要计算len(num)),而单个整数没有长度属性,所以触发TypeError。结合代码逻辑,你的需求应该是先对整个num列表排序,再用outln逐行打印排序后的元素,而非对单个整数排序。

修正后的代码

from sys import stdin, stdout

def readln():
  return stdin.readline().rstrip()

def outln(n):
  stdout.write(str(n))
  stdout.write("\n")

def sort(num):
  menor = []
  igual = []
  maior = []
  if len(num) > 1:
    pivot = num[0]
    for x in num:
      if x < pivot:
        menor.append(x)
      elif x == pivot:
        igual.append(x)
      elif x > pivot:
        maior.append(x)
    return sort(menor) + igual + sort(maior)
  else:
    return num

nnum = int(input(""))
num = []

for i in range(nnum):
  numeros = int(input(""))
  num.append(numeros)

# 先对整个num列表排序,得到排序后的新列表
sorted_num = sort(num)
# 遍历排序后的列表,用outln逐行打印每个元素
for x in sorted_num:
  outln(x)

关键修改点

将原代码中for x in num: outln(sort(x))的逻辑拆分:先调用sort(num)对整个列表排序,得到排序后的列表sorted_num,再遍历该列表用outln打印每个元素。这样既保证sort函数接收的是合法的列表参数,也满足你用outln逐行打印元素的需求。

内容的提问来源于stack exchange,提问作者Fausto Faustino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:40:32