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

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

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


当前回答

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

其他回答

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

你正在处理一个python列表,对它排序就像这样简单。

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

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