Python:如何在没有排序功能的情况下对列表中的字母排序? [英] Python: How to sort the alphabet in a list without sorted functions?

查看:104
本文介绍了Python:如何在没有排序功能的情况下对列表中的字母排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是基于效率的,必须仅使用非常非常基本的python知识(字符串,元组,列表基础)来完成,因此无需导入函数或使用排序/排序. (这是使用Python 2.7.3).

This is not based on efficiency, and has to be done with only a very very basic knowledge of python (Strings, Tuples, Lists basics) so no importing functions or using sort/sorted. (This is using Python 2.7.3).

例如,我有一个列表:

unsort_list = ["B", "D", "A", "E", "C"]
sort_list = []

sort_list需要能够打印出:

sort_list needs to be able to print out:

"A, B, C, D, E"

我可以用数字/整数来做,是否有类似的方法来处理字母顺序字符串?如果没有的话,在不导入或排序功能的情况下,您会推荐什么(即使效率不高.).

I can do it with numbers/integers, is there a similar method for alphabetical order strings? if not what would you recommend (even if it isn't efficient.) without importing or sort functions.

推荐答案

这是 Quicksort的非常简短的实现 Python中的算法:

Here's a very short implementation of the Quicksort algorithm in Python:

def quicksort(lst):
    if not lst:
        return []
    return (quicksort([x for x in lst[1:] if x <  lst[0]])
            + [lst[0]] +
            quicksort([x for x in lst[1:] if x >= lst[0]]))

这是一种玩具实现方式,易于理解,但效率低下,无法在实践中使用.它更多地是作为一项学术练习来展示如何以函数式编程风格简洁地编写排序问题的解决方案.它将适用于可比较对象的列表,尤其是针对问题:

It's a toy implementation, easy to understand but too inefficient to be useful in practice. It's intended more as an academic exercise to show how a solution to the problem of sorting can be written concisely in a functional programming style. It will work for lists of comparable objects, in particular for the example in the question:

unsort_list = ['B', 'D', 'A', 'E', 'C']
sort_list   = quicksort(unsort_list)

sort_list
> ['A', 'B', 'C', 'D', 'E']

这篇关于Python:如何在没有排序功能的情况下对列表中的字母排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆