TypeError: 不支持的操作数类型 -: 'str' 和 'int' (Python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42219874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: unsupported operand type(s) for -: 'str' and 'int' (Python)
提问by Devendra Bhat
I have written the code for quick sort in python, but this code is throwing an error.
我已经在 python 中编写了快速排序的代码,但是这段代码抛出了一个错误。
----------
k=0
def partition(arr,low_index,high_index):
key = arr[low_index]
i = low_index + 1;
j = high_index
while True:
while (i<high_index and key>=arr[i]):
i+=1
while (key<arr[j]):
j-=1
if i<j:
arr[i,j] = arr[j,i]
else:
arr[low_index,j]=arr[j,low_index]
return j
def quicksort(arr,low_index,high_index):
if low_index < high_index:
j = partition(low_index,high_index,arr)
print("Pivot element with index "+str(j)+" has thread "+str(k))
if left<j:
k=k+1
quicksort(arr,low_index, j - 1)
if i<right:
k=k+1
quicksort(arr,j+1,high_index)
return arr
n = input("Enter the value n ")
arr=input("Enter the "+str(n)+" no. of elements ")
brr=quicksort(arr,0,n-1)
print("Elements after sorting are "+str(brr))
----------
The error it is throwing is
它抛出的错误是
Enter the value n 4
Enter the 4 no. of elements [5,6,2,7] Traceback (most recent call last): File "C:\Users\devendrabhat\Documents\dev\dev\quick.py", line 38, in brr=quicksort(arr,0,n-1) TypeError: unsupported operand type(s) for -: 'str' and 'int'
输入值 n 4
输入 4 号。元素 [5,6,2,7] 回溯(最近一次调用最后一次):文件“C:\Users\devendrabhat\Documents\dev\dev\quick.py”,第 38 行,在 brr=quicksort(arr,0 ,n-1) TypeError: 不支持的操作数类型 -: 'str' 和 'int'
回答by Nick Hale
You need to change n to an integer, not a string. Your error is telling you, that you are trying to perform an operation (- in this case) on a string and an integer. Change str(n)
to int(n)
so you have the same type throughout.
您需要将 n 更改为整数,而不是字符串。您的错误告诉您,您正在尝试对字符串和整数执行操作(在本例中为 - )。更改str(n)
为int(n)
使您始终具有相同的类型。
回答by Hironsan
n is string. So you need to change it to int:
n 是字符串。所以你需要把它改成int:
n = int(n)
If you input [5,6,2,7] on line 37, python interpret it as string like "[5,6,2,7]". So, you need to convert string to list.
如果在第 37 行输入 [5,6,2,7],python 会将其解释为类似“[5,6,2,7]”的字符串。因此,您需要将字符串转换为列表。
arr = eval(arr)
回答by Venkatesh_CTA
you are declaring 'n' as string there in your code. And trying to perform arithmetic operation with string.
您在代码中将 'n' 声明为字符串。并尝试用字符串执行算术运算。
So it is giving that error. Change this str(n)
to int(n)
.
所以它给出了那个错误。将此更改str(n)
为int(n)
.
It will work !!!
它会起作用!!!