【问题标题】:Python data structure sort list alphabeticallyPython数据结构按字母顺序排序列表
【发布时间】:2012-12-11 12:51:05
【问题描述】:

我对python中的数据结构有点困惑; ()[]{}。我正在尝试对一个简单的列表进行排序,可能是因为我无法识别我无法对其进行排序的数据类型。

我的清单很简单:['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']

我的问题是这是什么类型的数据,以及如何按字母顺序对单词进行排序?

【问题讨论】:

标签: python list sorting alphabetical


【解决方案1】:

Python 有一个名为 sorted 的内置函数,它会根据您提供给它的任何可迭代对象(例如列表 ([1,2,3]);字典 ({1:2,3:4},尽管它只是返回键的排序列表;一个集合 ({1,2,3,4);或一个元组 ((1,2,3,4)))。

>>> x = [3,2,1]
>>> sorted(x)
[1, 2, 3]
>>> x
[3, 2, 1]

列表也有一个 sort 方法,它将执行就地排序(x.sort() 返回 None 但会更改 x 对象)。

>>> x = [3,2,1]
>>> x.sort()
>>> x
[1, 2, 3]

两者都采用key 参数,它应该是一个可调用的(函数/lambda),您可以使用它来更改排序依据。
例如,要从按值排序的字典中获取(key,value)-pairs 列表,您可以使用以下代码:

>>> x = {3:2,2:1,1:5}
>>> sorted(x.items(), key=lambda kv: kv[1])  # Items returns a list of `(key,value)`-pairs
[(2, 1), (3, 2), (1, 5)]

【讨论】:

    【解决方案2】:

    ListName.sort() 将按字母顺序对其进行排序。您可以在括号中添加reverse=False/True来颠倒项目的顺序:ListName.sort(reverse=False)

    【讨论】:

    • 这是对 Ruby 的评论吗?
    【解决方案3】:

    [] 表示list() 表示tuple{} 表示dictionary。你应该看看official Python tutorial,因为这些是 Python 编程的基础知识。

    你所拥有的是一个字符串列表。你可以这样排序:

    In [1]: lst = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
    
    In [2]: sorted(lst)
    Out[2]: ['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
    

    如您所见,以大写字母开头的单词优先于以小写字母开头的单词。如果您想对它们进行独立排序,请执行以下操作:

    In [4]: sorted(lst, key=str.lower)
    Out[4]: ['constitute', 'Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim']
    

    您还可以通过执行以下操作以相反的顺序对列表进行排序:

    In [12]: sorted(lst, reverse=True)
    Out[12]: ['constitute', 'Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux']
    
    In [13]: sorted(lst, key=str.lower, reverse=True)
    Out[13]: ['Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux', 'constitute']
    

    请注意:如果您使用 Python 3,那么 str 是包含人类可读文本的每个字符串的正确数据类型。但是,如果您仍然需要使用 Python 2,那么您可能会处理 Python 2 中数据类型为 unicode 而不是 str 的 unicode 字符串。在这种情况下,如果你有一个 unicode 字符串列表,你必须写 key=unicode.lower 而不是 key=str.lower

    【讨论】:

    • 在来自 MongoDB 数据库的 pymongo find_one() 结果上使用第二个示例,我收到错误:descriptor 'lower' requires a 'str' object but received a 'unicode'。结果是一个字符串数组,实现如下:results['keywords'] = sorted(keywords['keywords'], key=str.lower)。有谁知道如何解决这个问题?
    • @user1063287 抱歉,我回复晚了。在您的情况下,您需要写 key=unicode.lower 而不是 key=str.lower。这是因为您正在处理 unicode 字符串,而不是字节字符串。更多信息请参考官方Unicode HOWTO,尤其是Python 2和3各自的区别。
    【解决方案4】:
    >>> a = ()
    >>> type(a)
    <type 'tuple'>
    >>> a = []
    >>> type(a)
    <type 'list'>
    >>> a = {}
    >>> type(a)
    <type 'dict'>
    >>> a =  ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'] 
    >>> a.sort()
    >>> a
    ['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
    >>> 
    

    【讨论】:

      【解决方案5】:

      您可以使用内置的sorted 函数。

      print sorted(['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'])
      

      【讨论】:

        【解决方案6】:

        您正在处理一个 python 列表,对其进行排序就像这样做一样简单。

        my_list = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
        my_list.sort()
        

        【讨论】: