我对python中的数据结构有点困惑;()、[]、{}。我试图排序一个简单的列表,可能因为我不能确定我未能排序的数据类型。

我的清单很简单:['Stem', ' comprise ', 'Sedge', ' evolx ', 'Whim', '阴谋']

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


当前回答

你可以使用内置排序函数。

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

其他回答

ListName.sort()将按字母顺序排序。你可以在括号中添加reverse=False/True来反转项目的顺序:

Python有一个名为sorted的内置函数,它将从你提供给它的任何可迭代对象(例如list ([1,2,3]);dict({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]

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

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

两者都有一个key参数,该参数应该是一个可调用的(function/lambda),您可以使用它来更改排序。 例如,要从字典中获得一个(key,value)-对列表,可以使用以下代码:

>>> 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)]
>>> 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']
>>> 

[]表示列表,()表示元组,{}表示字典。你应该看一看官方的Python教程,因为这些是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的unicode字符串,而不是str。在这种情况下,如果你有一个unicode字符串列表,你必须写key=unicode。Lower代替key=str.lower。

你可以使用内置排序函数。

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