使用函数sorted()对列表进行临时排序

要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,可使用函数sorted()。函数sorted()让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。

下面尝试对汽车列表调用这个函数。

cars = ['bmw', 'audi', 'toyota', 'subaru']

print("Here is the original list:") ❶

print(cars)

print("\nHere is the sorted list:") ❷

print(sorted(cars))

print("\nHere is the original list again:") ❸

print(cars)

我们首先按原始顺序打印列表(见❶),再按字母顺序显示该列表(见❷)。以特定顺序显示列表后,我们进行核实,确认列表元素的排列顺序与以前相同(见❸)。

Here is the original list:

['bmw', 'audi', 'toyota', 'subaru']

Here is the sorted list:

['audi', 'bmw', 'subaru', 'toyota']

Here is the original list again: ❹

['bmw', 'audi', 'toyota', 'subaru']

注意,调用函数sorted()后,列表元素的排列顺序并没有变(见❹)。如果你要按与字母顺序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True。

注意 在并非所有的值都是小写时,按字母顺序排列列表要复杂些。决定排列顺序时,有多种解读大写字母的方式,要指定准确的排列顺序,可能比我们这里所做的要复杂。然而,大多数排序方式都基于本节介绍的知识。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容