无法将“int”转换为字符串

2024-04-18 03:33:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python有点陌生,因为我是攻读GCSE计算机科学的10年级学生。我正在尝试编写冒泡排序算法,但在TypeError: Can't convert 'int' object to str implicitly处遇到了障碍,我没有任何线索,因为我已经使用isinstance()检查了xlength,它们都是整数。快来人救命!:)

以下是我目前的代码:

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

Tags: 算法convertifcanlength学生listint
2条回答

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需要字符串iterable。但是,您的list1是一个整数列表。所以结果就出了问题。你知道吗

您可以通过将列表的元素映射到str等价项来修复错误本身,方法是:

print("The sorted list is - ",''.join(map(str, list1))

但话说回来,代码很容易出错:

  1. 在遍历列表时添加和删除项目
  2. 使用x既可以计算有序的元素,也可以交换元素
  3. 在气泡循环之后,您永远不会重置x,因此将对气泡计数两次。你知道吗
  4. 此外,捕捉IndexError非常不雅观,因为您还可以限制i的范围。你知道吗

更优雅的解决方案可能是:

unsorted = True
while unsorted:
    unsorted = False  # declare the list sorted
                      # unless we see a bubble that proves otherwise
    for i in range(len(l)-1):  # avoid indexerrors
        if l[i] > l[i+1]:
            unsorted = True  # the list appears to be unsorted
            l[i+1], l[i] = l[i], l[i+1]  # swap elements

print(l)  # print the list using repr

相关问题 更多 >