【问题标题】:How can i sort in python without using sort function如何在不使用排序功能的情况下在 python 中排序
【发布时间】:2018-12-02 09:37:01
【问题描述】:

我正在尝试按升序对列表进行排序,但存在一些问题。我怎样才能准确地修复它们。

代码如下所示。请帮助我。

def Sorting_a_List(input_list):
  My_List=[]
  b=[]
  for k in range(0,len(input_list)):
    for a in range(0,len(input_list)-1):
        if input_list[k]<input_list[a+1]:
            a=a+1
        else:
            b=input_list[k]
            input_list[k]=input_list[a+1]
            input_list[a+1]=b
  return input_list

【问题讨论】:

  • 你不使用sort的动机是什么?
  • 缩进无效。这是你要问的问题吗?
  • 我的意思是当我将输入作为 [3,8,2,7] 时,输出将是 [2,8,3,7]
  • 我试图在没有排序功能的情况下处理(因为在 edx 平台上给出了类似的问题)
  • 实际上我现在意识到错误地粘贴了代码。我们可以没有缩进问题。只是代码功能不正确

标签: python sorting bubble-sort


【解决方案1】:

这里是代码。我做了尽可能少的更改,以便您更容易理解。只需按原样复制-保存-运行此代码:

def Sorting_a_List(input_list):
    for k in range(0,len(input_list)):
        for a in range(0,len(input_list)-1):
            if input_list[k]>input_list[a]:
                continue
            else:
                b=input_list[k]
                input_list[k]=input_list[a]
                input_list[a]=b
    return input_list

# If you just need the function, then skip copying the lines below!
input_list = input("Enter the list separated by space: ").split()
input_list = list(map(int,input_list))
print("Your list in Ascending order:",Sorting_a_List(input_list))

上面的代码(基于你的代码)看起来很忙,所以下面只是一个使用冒泡排序的更清晰的版本:

def bubble_sort(inputList):
    index = len(inputList) - 1
    while index >= 0:
        for j in range(index):
            if inputList[j] > inputList[j+1]:
                inputList[j], inputList[j+1] = inputList[j+1], inputList[j]
        index -= 1
    return inputList

# If you just need the function, then skip copying the lines below!
inputList = input("Enter the list separated by space: ").split()
inputList = list(map(int,inputList))
print("Your list in Ascending order:",bubble_sort(inputList))

希望这会有所帮助!

【讨论】:

  • 非常感谢您的关注。
  • 不客气。你可以接受它作为最佳答案,如果它对你有帮助,也可以点赞!
  • 是的,它有帮助。之后我也可以编写这样的代码。
猜你喜欢
  • 1970-01-01
  • 2021-12-15
  • 2021-12-12
  • 2014-07-28
  • 2020-02-25
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多