Python 数据结构按字母顺序排序列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14032521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:13:51  来源:igfitidea点击:

Python data structure sort list alphabetically

pythonlistsortingalphabetical

提问by icypy

I am a bit confused regarding data structure in python; (),[], and {}. I am trying to sort a simple list, probably since I cannot identify the type of data I am failing to sort it.

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

My list is simple: ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']

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

My question is what type of data this is, and how to sort the words alphabetically?

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

采纳答案by pemistahl

[]denotes a list, ()denotes a tupleand {}denotes a dictionary. You should take a look at the official Python tutorialas these are the very basics of programming in Python.

[]表示一个列表()表示一个元组{}表示一个字典。您应该查看官方 Python 教程,因为这些是 Python 编程的基础知识。

What you have is a list of strings. You can sort it like this:

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

In [1]: lst = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']

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

As you can see, words that start with an uppercase letter get preference over those starting with a lowercase letter. If you want to sort them independently, do this:

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

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

You can also sort the list in reverse order by doing this:

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

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

Please note:If you work with Python 3, then stris the correct data type for every string that contains human-readable text. However, if you still need to work with Python 2, then you might deal with unicode strings which have the data type unicodein Python 2, and not str. In such a case, if you have a list of unicode strings, you must write key=unicode.lowerinstead of key=str.lower.

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

回答by Bryan

You're dealing with a python list, and sorting it is as easy as doing this.

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

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

回答by Fatih Erikli

You can use built-in sortedfunction.

您可以使用内置sorted函数。

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

回答by Abhijeet Rastogi

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

回答by Teo Klestrup R?ijezon

Python has a built-in function called sorted, which will give you a sorted list from any iterable you feed it (such as a list ([1,2,3]); a dict ({1:2,3:4}, although it will just return a sorted list of the keys; a set ({1,2,3,4); or a tuple ((1,2,3,4))).

Python 有一个名为 的内置函数sorted,它会从你提供给它的任何可迭代对象中得到一个排序列表(例如一个列表 ( [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]

Lists also have a sortmethod that will perform the sort in-place (x.sort() returns None but changes the x object) .

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

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

Both also take a keyargument, which should be a callable (function/lambda) you can use to change what to sort by.
For example, to get a list of (key,value)-pairs from a dict which is sorted by value you can use the following code:

两者都带有一个key参数,它应该是一个可调用的(函数/lambda),您可以使用它来更改要排序的内容。
例如,(key,value)要从按值排序的 dict 中获取-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)]

回答by Crafter0800

ListName.sort()will sort it alphabetically. You can add reverse=False/Truein the brackets to reverse the order of items: ListName.sort(reverse=False)

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