TypeError:必须是str,而不是s中的int

2024-10-03 13:16:56 发布

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

我在排序算法(气泡排序)的Python代码中遇到了这种错误

Traceback (most recent call last): File "D:\CSC\PYTHON SAMPLE CODES\bubstepbystep.py", line 13, in nlist = nlist + i TypeError: must be str, not int

我不知道里面发生了什么。请帮帮我。你知道吗

import time

nlist = input("Enter series of numbers: ")
swap = len(nlist)
qty = len(nlist)
print("Original:", nlist)


for x in range(qty - 1):
    for i in range(swap - 1):  #swap
    if nlist [i] > nlist [i+1]:
        temp = nlist [i]
        nlist = nlist + i
        nlist [i+1] = temp

        print("\nSwapping Index:", i,"and", i+1, "\n\rNew list:", nlist)
        time.sleep(3)
    else:
        print("\nSwapping Index:", i,"and", i+1)
        time.sleep(3)
        print("Nothing to swap, skipping . . .")
        time.sleep(3)

swap -= 1

Tags: andinforindexlentime排序range
1条回答
网友
1楼 · 发布于 2024-10-03 13:16:56

你的问题是你的输入,我认为:把它映射到正确的整数,事情看起来就好多了。此外,您的交换代码不正确:

import time

nlist = list(map(int, input("Enter series of numbers: ").split()))
nlist 
swap = len(nlist)
qty = len(nlist)
print("Original:", nlist)

for x in range(qty - 1):
    for i in range(swap - 1):  #swap
        if nlist [i] > nlist [i+1]:
            temp = nlist [i]
            print(temp)
            nlist [i] = nlist [i+1]
            nlist [i+1] = temp

            print("\nSwapping Index:", i,"and", i+1, "\n\rNew list:", nlist)
            time.sleep(3)
        else:
            print("\nSwapping Index:", i,"and", i+1)
            time.sleep(3)
            print("Nothing to swap, skipping . . .")
            time.sleep(3)

swap -= 1

print("Final:", nlist)

相关问题 更多 >