【问题标题】:Can't convert 'int' to string无法将“int”转换为字符串
【发布时间】:2018-05-10 01:44:17
【问题描述】:

我正在尝试编写冒泡排序算法,但我在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

【问题讨论】:

  • 请不要在迭代列表时更改列表。此外,您在这里使用x 有两个目的:计算已排序的实例和交换元素。
  • 您正在尝试在此处为 x 分配一个字符串值:x = list1[i]。列表list1 是字符串列表,而不是整数。
  • 这段代码在 python 3 上运行正常,你是在 python2 上使用这段代码吗?
  • 哦,是的,我使用 x 两次 Willem。因此,如果我使用 int(input()) 然后创建一个列表,它应该可以工作吗?我正在使用 python 3 是的,谢谢大家!

标签: python string int typeerror bubble-sort


【解决方案1】:

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'
>>> 

【讨论】:

    【解决方案2】:

    错误出现在join(list1) 调用中。 str.join 期望 字符串 的迭代。但是,您的 list1 是一个整数列表。结果就出错了。

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

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

    但话虽如此,代码很容易出错:

    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

    【讨论】:

    • 所以看别人怎么说,把list(input()改成int(input()再转换成列表。然后使用您的方法映射元素并交换元素。谢谢!
    猜你喜欢
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2017-02-04
    相关资源
    最近更新 更多