def sort(nums):
finish = False
while finish == False:
finish = True
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
t = nums[i]
nums[i] = nums[i+1]
nums[i+1] = t
finish = False
print(nums)
return nums
9显然不大于101,所以我不知道为什么它会不断被交换
答案 0 :(得分:1)
如评论中所述,排序问题源于以下事实:您的输入是string
而不是int
的列表。您可以使用list comprehesion
轻松地转换值。
另外两个注释:1)与其他编程语言不同,在python
中,您不需要使用临时变量来切换两个变量的值,您可以用1行而不是3行。 2)使用while True
结构而不在循环前预先定义特殊变量(例如“ finish”),并使用break
子句退出循环是更受欢迎的。
这是固定和修改的代码:
def sort(nums):
nums = [int(n) for n in nums] #This is the neccesary line to fix the bug you are having
while True:
finish = True
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
finish = False
print(nums)
if finish:
break
return nums
l = ['1', '101', '9', '808', '54']
sort(l)
输出:
[1, 9, 101, 808, 54]
[1, 9, 101, 54, 808]
[1, 9, 54, 101, 808]
Out[17]:
[1, 9, 54, 101, 808]