【sort()方法与sorted()函数】数组sort()方法使用后报错object of type ‘NoneType‘

场景:
美团笔试题——正则序列
下面的代码运行后报错【TypeError: object of type ‘NoneType’ has no len()】

分析:
len(sorted_list)处的错误,意为sorted_list为NoneType
往上找sorted_list的定义,sorted_list=list(map(int,s.split())).sort()

def minopt(s):
    if s is None:
        return
    sorted_list=list(map(int,s.split())).sort()
    res=0
    for i in range(1,len(sorted_list)+1):
        res+=abs(i-sorted_list[i-1])
    return res
n=int(input())
s=input()
print(minopt(s))

原因:
数组对象使用sort()方法后,不会返回一个新的对象,只是改变原数组的值。
参考下面的示例来理解:
在这里插入图片描述

解决方法:

  1. 使用sorted()函数,它会产生一个新的列表对象而不改变原列表的大小。
  2. 继续使用sort()方法,取消赋值操作,分为两步,先将控制台输入处理为list对象sorted_list=list(map(int,s.split()))
    再对list对象使用sort方法,不进行赋值操作!sorted_list.sort()

此处用的方法2

def minopt(s):
    if s is None:
        return
    sorted_list=list(map(int,s.split()))
    sorted_list.sort()
    res=0
    for i in range(1,len(sorted_list)+1):
        res+=abs(i-sorted_list[i-1])
    return res
n=int(input())
s=input()
print(minopt(s))

区分sorted()函数与数组的sort()方法
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值