问题描述
我对python中的数据结构有点困惑;()
、[]
和 {}
.我正在尝试对一个简单的列表进行排序,可能是因为我无法识别无法对其进行排序的数据类型.
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.
我的清单很简单:['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
我的问题是这是什么类型的数据,以及如何按字母顺序对单词进行排序?
My question is what type of data this is, and how to sort the words alphabetically?
推荐答案
[]
表示 list, ()
表示一个 元组 和 {}
表示 字典.您应该查看官方 Python 教程,因为这些是 Python 的基础知识用 Python 编程.
[]
denotes a list, ()
denotes a tuple and {}
denotes a dictionary. You should take a look at the official Python tutorial as these are the very basics of programming in 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']
请注意:如果您使用 Python 3,则 str
是包含人类可读文本的每个字符串的正确数据类型.但是,如果您仍然需要使用 Python 2,那么您可能会处理在 Python 2 中具有数据类型 unicode
而不是 str
的 unicode 字符串.在这种情况下,如果您有一个 unicode 字符串列表,则必须编写 key=unicode.lower
而不是 key=str.lower
.
Please note: If you work with Python 3, then str
is 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 unicode
in Python 2, and not str
. In such a case, if you have a list of unicode strings, you must write key=unicode.lower
instead of key=str.lower
.
这篇关于Python 数据结构按字母顺序排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!