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

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

本文介绍了Python数据结构按字母顺序排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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?

推荐答案

[]表示列表()表示元组{}表示词典.您应该看一下官方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数据结构按字母顺序排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 14:35