[]
表示一个list http://docs.python.org/3/tutorial/introduction.html#lists, ()
表示一个tuple http://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences and {}
表示一个字典 http://docs.python.org/3/tutorial/datastructures.html#dictionaries。你应该看看官方Python教程 http://docs.python.org/3/tutorial/index.html因为这些是 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,那么您可能会处理具有以下数据类型的 unicode 字符串unicode
在 Python 2 中,而不是str
。在这种情况下,如果您有 unicode 字符串列表,则必须编写key=unicode.lower
代替key=str.lower
.