【发布时间】:2018-05-10 01:44:17
【问题描述】:
我正在尝试编写冒泡排序算法,但我在TypeError: Can't convert 'int' object to str implicitly 上磕磕绊绊,我不知道,因为我已经使用isinstance() 检查了x 和length,它们都是整数。
到目前为止,这是我的代码:
x = 1
list1 = list(input("What numbers need sorting? Enter them as all one - "))
length = len(list1)
print(list1)
while True:
for i in range(0,length):
try:
if list1[i] > list1[i+1]:
x = list1[i]
list1.remove(x)
list1.insert(i+1,x)
print(list1)
if list1[i] < list1[i+1]:
x += 1
print(list1)
except IndexError:
break
if x == length:
print("The sorted list is - ",''.join(list1))
break
【问题讨论】:
-
请不要在迭代列表时更改列表。此外,您在这里使用
x有两个目的:计算已排序的实例和交换元素。 -
您正在尝试在此处为
x分配一个字符串值:x = list1[i]。列表list1是字符串列表,而不是整数。 -
这段代码在 python 3 上运行正常,你是在 python2 上使用这段代码吗?
-
哦,是的,我使用 x 两次 Willem。因此,如果我使用
int(input())然后创建一个列表,它应该可以工作吗?我正在使用 python 3 是的,谢谢大家!
标签: python string int typeerror bubble-sort