python - 在没有排序功能的情况下在python中对列表进行排序

标签 python list sorting

import sys
import pdb

a = [5, 2, 4, 1]

for i in range(len(a)):
    for j in range(len(a) - 1):
        if a[j] > a[j+1]:
            t = a[j]
            a[j] = a[j+1] 
            a[j] = t

print a                   
sys.exit()

我刚刚在 Python 中尝试了一个 C 程序——一个没有 sorted 函数的普通排序。为什么我没有得到排序列表?

最佳答案

t = a[j]

其次是

a[j] = t

好像不太对。如果你想交换它们,第二个应该是:

a[j + 1] = t

但是在 Python 中,最好写成:

a[j], a[j + 1] = a[j + 1], a[j]

(当然,在 Python 中, 写成快速排序要好得多。)

关于python - 在没有排序功能的情况下在python中对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20257558/

相关文章:

python - 在 Tornado 中接受 "Content-Encoding: gzip"

android - 创建按字母顺序排序歌曲的 ListView android

c# - 以特殊格式对字符串数组进行排序

python - 将行 reshape 为 Pandas 数据框中的列

python - 解码Jpeg/内容: 0 'refers to a tensor that does not exist

python - 有效地计算小于给定值的列表条目

list - 在 Prolog 中将普通树转换为列表

algorithm - 为 n 个数据点中的每一个排序 n-1 个最近的邻居

python - c/Python 等价于这样的循环?

python - 使用Python计算列表中重复子列表的数量