无法将 'int' 转换为字符串
Can't convert 'int' to string
我正在尝试编写冒泡排序算法的代码,但我在 TypeError: Can't convert 'int' object to str implicitly
上磕磕绊绊,我没有任何线索,因为我已经使用 [= 检查了 x
和 length
15=] 都是整数。
到目前为止,这是我的代码:
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
list1
由整数组成(大概;这取决于用户输入的内容,但代码的大部分编写就像它期望整数列表一样)但是您使用 ''.join
它好像包含字符串:
>>> ''.join([0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> ''.join(['0'])
'0'
>>>
错误在 join(list1)
调用中。 str.join
需要一个 可迭代的 字符串 。然而,您的 list1
是一个整数列表。所以结果就出错了。
您可以通过将列表的元素映射到 str
等价物来修复错误,方法是:
print("The sorted list is - ",''.join(<b>map(str, </b>list1<b>)</b>)
但话说回来,代码很容易出错:
- 您在遍历列表时添加和删除项目;
- 您使用
x
来计算有序元素和交换元素;
- 你永远不会在气泡循环后重置
x
,所以你会计算两次气泡。
- 此外,捕获
IndexError
非常不优雅,因为您还可以限制 i
. 的范围
可能更优雅的解决方案是:
<b>unsorted = True</b>
while <b>unsorted</b>:
<b>unsorted = False</b> # declare the list sorted
# unless we see a bubble that proves otherwise
for i in range(len(l)<b>-1</b>): # avoid indexerrors
if l[i] > l[i+1]:
<b>unsorted = True</b> # the list appears to be unsorted
<b>l[i+1], l[i] = l[i], l[i+1]</b> # swap elements
print(l) # print the list using repr
我正在尝试编写冒泡排序算法的代码,但我在 TypeError: Can't convert 'int' object to str implicitly
上磕磕绊绊,我没有任何线索,因为我已经使用 [= 检查了 x
和 length
15=] 都是整数。
到目前为止,这是我的代码:
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
list1
由整数组成(大概;这取决于用户输入的内容,但代码的大部分编写就像它期望整数列表一样)但是您使用 ''.join
它好像包含字符串:
>>> ''.join([0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> ''.join(['0'])
'0'
>>>
错误在 join(list1)
调用中。 str.join
需要一个 可迭代的 字符串 。然而,您的 list1
是一个整数列表。所以结果就出错了。
您可以通过将列表的元素映射到 str
等价物来修复错误,方法是:
print("The sorted list is - ",''.join(<b>map(str, </b>list1<b>)</b>)
但话说回来,代码很容易出错:
- 您在遍历列表时添加和删除项目;
- 您使用
x
来计算有序元素和交换元素; - 你永远不会在气泡循环后重置
x
,所以你会计算两次气泡。 - 此外,捕获
IndexError
非常不优雅,因为您还可以限制i
. 的范围
可能更优雅的解决方案是:
<b>unsorted = True</b>
while <b>unsorted</b>:
<b>unsorted = False</b> # declare the list sorted
# unless we see a bubble that proves otherwise
for i in range(len(l)<b>-1</b>): # avoid indexerrors
if l[i] > l[i+1]:
<b>unsorted = True</b> # the list appears to be unsorted
<b>l[i+1], l[i] = l[i], l[i+1]</b> # swap elements
print(l) # print the list using repr