场景:
美团笔试题——正则序列
下面的代码运行后报错【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()方法后,不会返回一个新的对象,只是改变原数组的值。
参考下面的示例来理解:
解决方法:
- 使用sorted()函数,它会产生一个新的列表对象而不改变原列表的大小。
- 继续使用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()方法