我正在编写一个未运行的merge_sort
程序。
它显示错误
if a[j] < b[k]:
TypeError:“ int”和“ list”的实例之间不支持“ <”
l=[int(n) for n in input().split()]
def merge_sort(l):
if len(l)==1:
return l
else:
a=l[:len(l)//2]
b=l[len(l)//2:]
print(a,b)
a=merge_sort(a)
b=merge_sort(b)
j=0
k=0
for i in range(0,len(l)):
if a[j] < b[k]:
l[i]=a[j]
j+=1
if j==len(a):
l=l.append(b[k:])
break
else:
l[i]=b[k]
k+=1
if k==len(b):
l=l.append(a[j:])
break
# print(l)
return l
print(merge_sort(l))
这是错误消息。
Traceback (most recent call last):
File "E:/STUFF/Python/Scripts/COURSERA/merge_sort.py", line 30, in <module>
print(merge_sort(l))
File "E:/STUFF/Python/Scripts/COURSERA/merge_sort.py", line 10, in merge_sort
merge_sort(b)
File "E:/STUFF/Python/Scripts/COURSERA/merge_sort.py", line 15, in merge_sort
if a[j] < b[k]:
TypeError: '<' not supported between instances of 'int' and 'list'
Process finished with exit code 1
答案 0 :(得分:1)
就像您在此处将整数列表附加到整数列表的末尾一样:
l=l.append(b[k:])
因此,如果l = [1,2,3]和b [k:] = [4,5],您将得到
l.append(b[k:])
Out:
[1, 2, 3, [4, 5]]
也list.append()返回None,并且您不需要将其分配给l。尝试使用
l.extend(b[k:])