Python类型错误为什么列表被视为函数(快速排序示例)
第一个问题!因此,我试图学习Python(来自Java使用的两个学期),我遇到了一个类型错误,我认为这是由于在应该有一个列表的情况下有一个函数造成的。以下是我的代码:Python类型错误为什么列表被视为函数(快速排序示例),python,Python,第一个问题!因此,我试图学习Python(来自Java使用的两个学期),我遇到了一个类型错误,我认为这是由于在应该有一个列表的情况下有一个函数造成的。以下是我的代码: t=[3,5,2,4,1] def快速排序(lst): 如果len(lst)==0: 返回[] pivot=[lst[0]] 左=[x代表lst中的x,如果x轴[0]] ans=快速排序(左)+枢轴+快速排序(右) 返回ans #返回快速排序(左)+轴+快速排序[右] 打印快速排序(t) 成功了。但当我这么做的时候: t = [
t=[3,5,2,4,1]
def快速排序(lst):
如果len(lst)==0:
返回[]
pivot=[lst[0]]
左=[x代表lst中的x,如果x轴[0]]
ans=快速排序(左)+枢轴+快速排序(右)
返回ans
#返回快速排序(左)+轴+快速排序[右]
打印快速排序(t)
成功了。但当我这么做的时候:
t = [3,5,2,4,1]
def quicksort(lst):
if len(lst) == 0:
return []
pivot = [lst[0]]
left = [x for x in lst if x < pivot[0]]
right = [x for x in lst if x > pivot[0]]
#ans = quicksort(left) + pivot + quicksort(right)
#return ans
return quicksort(left) + pivot + quicksort[right]
print quicksort(t)
t=[3,5,2,4,1]
def快速排序(lst):
如果len(lst)==0:
返回[]
pivot=[lst[0]]
左=[x代表lst中的x,如果x轴[0]]
#ans=快速排序(左)+枢轴+快速排序(右)
#返回ans
返回快速排序(左)+轴+快速排序[右]
打印快速排序(t)
我明白了:
Traceback (most recent call last):
File "quickSortTest.py", line 13, in <module>
print quicksort(t)
File "quickSortTest.py", line 11, in quicksort
return quicksort(left) + pivot + quicksort[right]
File "quickSortTest.py", line 11, in quicksort
return quicksort(left) + pivot + quicksort[right]
File "quickSortTest.py", line 11, in quicksort
return quicksort(left) + pivot + quicksort[right]
TypeError: 'function' object is unsubscriptable
回溯(最近一次呼叫最后一次):
文件“quickSortTest.py”,第13行,在
打印快速排序(t)
文件“quickSortTest.py”,第11行,在快速排序中
返回快速排序(左)+轴+快速排序[右]
文件“quickSortTest.py”,第11行,在快速排序中
返回快速排序(左)+轴+快速排序[右]
文件“quickSortTest.py”,第11行,在快速排序中
返回快速排序(左)+轴+快速排序[右]
TypeError:“函数”对象不可订阅
我想了解其中的区别,非常感谢您的解释
-
您在这里使用了括号而不是括号。括号用于索引和切片;括号用于函数调用
Traceback (most recent call last):
File "quickSortTest.py", line 13, in <module>
print quicksort(t)
File "quickSortTest.py", line 11, in quicksort
return quicksort(left) + pivot + quicksort[right]
File "quickSortTest.py", line 11, in quicksort
return quicksort(left) + pivot + quicksort[right]
File "quickSortTest.py", line 11, in quicksort
return quicksort(left) + pivot + quicksort[right]
TypeError: 'function' object is unsubscriptable
quicksort[right]