龙空技术网

一日一技:Python中的列表排序

Python编程之美 117

前言:

现在我们对“python二维list排序”大约比较注意,你们都需要分析一些“python二维list排序”的相关资讯。那么小编在网摘上汇集了一些关于“python二维list排序””的相关内容,希望各位老铁们能喜欢,同学们快快来学习一下吧!

两种排序方法:sort和sorted

分别举例说明一下:sort

words = ['forest', 'wood', 'tool', 'arc', 'sky', 'poor', 'cloud', 'rock']vals = [2, 1, 0, 3, 4, 6, 5, 7]words.sort()print(words)vals.sort()print(vals)

输出结果:

['arc', 'cloud', 'forest', 'poor', 'rock', 'sky', 'tool', 'wood'][0, 1, 2, 3, 4, 5, 6, 7]

再看sorted,举例如下:

words = ['forest', 'wood', 'brisk', 'tree', 'sky', 'cloud', 'rock', 'falcon']sorted_words = sorted(words)print('Original:', words)print('Sorted:', sorted_words)

输出结果也如下:

Original: ['forest', 'wood', 'brisk', 'tree', 'sky', 'cloud', 'rock', 'falcon']Sorted: ['brisk', 'cloud', 'falcon', 'forest', 'rock', 'sky', 'tree', 'wood']

我们再来看看python列表中的升序和降序排列。

Python列表中的升序/降序排序。

升序/降序由reverse选项控制,举例说明,如下:

words = ['forest', 'wood', 'tool', 'arc', 'sky', 'poor', 'cloud', 'rock']words.sort()print(words)words.sort(reverse=True)print(words)

执行结果如下:

['arc', 'cloud', 'forest', 'poor', 'rock', 'sky', 'tool', 'wood']['wood', 'tool', 'sky', 'rock', 'poor', 'forest', 'cloud', 'arc']

Python列表中的日期排序。

from datetime import datetimevalues = ['8-Nov-19', '21-Jun-16', '1-Nov-18', '7-Apr-19']values.sort(key=lambda d: datetime.strptime(d, "%d-%b-%y"))print(values)

输出结果:

['21-Jun-16', '1-Nov-18', '7-Apr-19', '8-Nov-19']

Python按元素索引排序列表

Python列表可以包含嵌套的可迭代项。 在这种情况下,我们可以选择应排序的元素。

vals = [(4, 0), (0, -2), (3, 5), (1, 1), (-1, 3)] vals.sort()print(vals)vals.sort(key=lambda e: e[1])print(vals)

该示例首先按嵌套元素的第一个元素排序,然后按第二个元素排序。

vals.sort(key=lambda e: e[1])

通过提供一个返回元组第二个元素的匿名函数,我们按元组的第二个值对元组进行排序。

输出结果如下:

[(-1, 3), (0, -2), (1, 1), (3, 5), (4, 0)][(0, -2), (4, 0), (1, 1), (-1, 3), (3, 5)]

Python按嵌套列表的总和排序列表

假设我们有嵌套的列表,它们都有一些不同的排名。 最终排名是所有值的总和,举例如下:

data = [[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [10, 9, 8, 7],     [6, 7, 8, 9], [5, 5, 5, 1], [5, 5, 5, 5], [3, 4, 5, 6], [10, 1, 1, 2]]data.sort()print(data)data.sort(key=sum)print(data)

默认情况下,排序功能按嵌套列表的第一个值排序。 为了实现我们的目标,我们将内置的sum函数传递给key选项。

输出结果如下:

[[3, 4, 5, 6], [5, 5, 5, 1], [5, 5, 5, 5], [6, 7, 8, 9], [8, 9, 10, 11], [9, 10, 11, 12], [10, 1, 1, 2], [10, 9, 8, 7], [10, 11, 12, 13]][[10, 1, 1, 2], [5, 5, 5, 1], [3, 4, 5, 6], [5, 5, 5, 5], [6, 7, 8, 9], [10, 9, 8, 7], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]

上面的实例显示了默认排序和自定义排序。

Python本地化字符串排序列表

对于支持区域设置的排序,我们可以将locale.strxfrm()用于关键函数。

import localewords = ['zem', 'čučoriedka', 'drevo', 'štebot', 'cesta', 'černice', 'ďateľ',     'rum', 'železo', 'prameň', 'sob']locale.setlocale(locale.LC_COLLATE, ('sk_SK', 'UTF8'))words.sort(key=locale.strxfrm)for word in words:    print (word)

该示例对斯洛伐克语单词Slovak words.进行排序,输出结果如下:

cestačernicečučoriedkaďateľdrevoprameňrumsobštebotzemželezo

注意:斯洛伐克语Slovak words单词的结果顺序并不完全正确。 字母ď在d之后。 这取决于对语言的支持程度。

Python列表中的字典排序.

在对字典进行排序时,我们可以选择执行排序的属性。

users = [  {'name': 'John Doe', 'date_of_birth': 1987},  {'name': 'Jane Doe', 'date_of_birth': 1996},  {'name': 'Robert Brown', 'date_of_birth': 1977},  {'name': 'Lucia Smith', 'date_of_birth': 2002},  {'name': 'Patrick Dempsey', 'date_of_birth': 1994}]users.sort(reverse=True, key=lambda e: e['date_of_birth']) for user in users:    print(user)

我们有一个用户users列表。 每个users用户列表由几个字典表示。

users.sort(reverse=True, key=lambda e: e['date_of_birth']) 

在匿名函数中,我们选择date_of_birth属性,输出结果如下:

{'name': 'Lucia Smith', 'date_of_birth': 2002}{'name': 'Jane Doe', 'date_of_birth': 1996}{'name': 'Patrick Dempsey', 'date_of_birth': 1994}{'name': 'John Doe', 'date_of_birth': 1987}{'name': 'Robert Brown', 'date_of_birth': 1977}

用户按照出生日期降序排序。

Python成绩列表排序

世界各地有各种分级系统。 我们的示例包含A +或C-等等级,因此无法按字典顺序排序。 我们使用一个字典,其中每个年级都有其给定的值。

data = 'A+   A    A-   B+   B   B-   C+    C    C-     D+   D'grades = { grade: idx for idx, grade in enumerate(data.split()) } def mc(e):    return grades.get(e[1])students = [('Anna', 'A+'), ('Jozef', 'B'), ('Rebecca', 'B-'), ('Michael', 'D+'),     ('Zoltan', 'A-'), ('Jan', 'A'), ('Michelle', 'C-'), ('Sofia', 'C+')]print(grades)students.sort(key=mc)print(students)# from operator import itemgetter# students.sort(key=lambda e: itemgetter(e[1])(grades))

输出结果如下:

{'A+': 0, 'A': 1, 'A-': 2, 'B+': 3, 'B': 4, 'B-': 5, 'C+': 6, 'C': 7, 'C-': 8, 'D+': 9, 'D': 10}[('Anna', 'A+'), ('Jan', 'A'), ('Zoltan', 'A-'), ('Jozef', 'B'), ('Rebecca', 'B-'), ('Sofia', 'C+'), ('Michelle', 'C-'), ('Michael', 'D+')]

Python按字符串长度排序列表

有时,我们需要按字符串的长度对其进行排序。

def w_len(e):  return len(e)words = ['forest', 'wood', 'tool', 'sky', 'poor', 'cloud', 'rock', 'if']words.sort(reverse=True, key=w_len)print(words)

在此示例中,我们不使用匿名函数。

def w_len(e):  return len(e)

w_len函数返回每个元素的长度,输出结果为:

['forest', 'cloud', 'wood', 'tool', 'poor', 'rock', 'sky', 'if']
单词按其长度降序排列。

默认情况下,首字母大写的字符串排在其他字符串之前。 无论大小写如何,我们都可以对字符串进行排序。

text = 'Today is a beautiful day. Andy went fishing.'words = text.replace('.', '')sorted_words = sorted(words.split(), key=str.lower)print('Case insensitive:', sorted_words)sorted_words2 = sorted(words.split())print('Case sensitive:', sorted_words2)

通过为key属性提供str.lower函数,我们执行不区分大小写的排序,输出结果如下:

Case insensitive: ['a', 'Andy', 'beautiful', 'day', 'fishing', 'is', 'Today', 'went']Case sensitive: ['Andy', 'Today', 'a', 'beautiful', 'day', 'fishing', 'is', 'went']

Python姓氏排序列表

在以下示例中,我们按姓氏对名称进行排序。

names = ['John Doe', 'Jane Doe', 'Robert Brown', 'Robert Novak',     'Lucia Smith', 'Patrick Dempsey', 'George Marshall', 'Alan Brooke',     'Harold Andras', 'Albert Doe']names.sort()names.sort(key=lambda e: e.split()[-1])for name in names:    print(name)

上面我们有一个名字列表。 每个名称都由名字和姓氏组成。 此外,还有几个姓氏相同的用户。 在这种情况下,我们希望按名字对它们进行排序。

names.sort()names.sort(key=lambda e: e.split()[-1])

首先,我们按名字对名字进行排序。 然后,我们按照名字的姓氏对其进行排序。 为此,我们分割每个字符串并选择最后一个字符串(索引为-1)。由于Python的排序算法稳定,因此记住了第一个排序并获得了预期的输出,结果如下:

Harold AndrasAlan BrookeRobert BrownPatrick DempseyAlbert DoeJane DoeJohn DoeGeorge MarshallRobert NovakLucia Smith

名称按其姓氏排序。 Doe用户按其名字正确排序。

Python 列表中的namedtuples.

在下一个示例中,我们对namedtuple进行排序,我们新建一个namedtuple_sort.py文件:

from typing import NamedTupleclass City(NamedTuple):    id: int    name: str    population: intc1 = City(1, 'Bratislava', 432000)c2 = City(2, 'Budapest', 1759000)c3 = City(3, 'Prague', 1280000)c4 = City(4, 'Warsaw', 1748000)c5 = City(5, 'Los Angeles', 3971000)c6 = City(6, 'Edinburgh', 464000)c7 = City(7, 'Berlin', 3671000)cities = [c1, c2, c3, c4, c5, c6, c7]cities.sort(key=lambda e: e.name)for city in cities:    print(city)

城市namedtuple具有三个属性:id,名称和人口。 该示例按名称元组的名称排序。

cities.sort(key=lambda e: e.name)

匿名函数返回namedtuple的name属性,输出结果如下:

City(id=7, name='Berlin', population=3671000)City(id=1, name='Bratislava', population=432000)City(id=2, name='Budapest', population=1759000)City(id=6, name='Edinburgh', population=464000)City(id=5, name='Los Angeles', population=3971000)City(id=3, name='Prague', population=1280000)City(id=4, name='Warsaw', population=1748000)

Python列表中的多种条件排序

下面的示例通过两个排序标准对学生列表进行排序。

from typing import NamedTuplefrom operator import attrgetterdef multi_sort(data, specs):    for key, reverse in reversed(specs):        data.sort(key=attrgetter(key), reverse=reverse)    return dataclass Student(NamedTuple):    id: int    name: str    grade: str    age: ints1 = Student(1, 'Patrick', 'A', 21)s2 = Student(2, 'Lucia', 'B', 19)s3 = Student(3, 'Robert', 'C', 19)s4 = Student(4, 'Monika', 'A', 22)s5 = Student(5, 'Thomas', 'D', 20)s6 = Student(6, 'Petra', 'B', 18)s6 = Student(7, 'Sofia', 'A', 18)s7 = Student(8, 'Harold', 'E', 22)s8 = Student(9, 'Arnold', 'B', 23)students = [s1, s2, s3, s4, s5, s6, s7, s8]multi_sort(students, (('grade', False), ('age', True)))for student in students:    print(student)

输出结果为:

Student(id=4, name='Monika', grade='A', age=22)Student(id=1, name='Patrick', grade='A', age=21)Student(id=7, name='Sofia', grade='A', age=18)Student(id=9, name='Arnold', grade='B', age=23)Student(id=2, name='Lucia', grade='B', age=19)Student(id=3, name='Robert', grade='C', age=19)Student(id=5, name='Thomas', grade='D', age=20)Student(id=8, name='Harold', grade='E', age=22)

Python自定义复杂对象的排序列表-硬币袋bags of coins

我们有一个自定义对象,一个namedtuple,它具有特定的排序方式。

注意:根据Python文档,进行排序时,sort和sorted仅使用__lt__ magic方法。 因此,我们仅需要实现此方法。 但是,PEP8建议执行所有六个操作(__eq__,__ne__,__lt__,__le__,__gt__,__ge__)以确保代码的安全性和完整性。

functools模块中的total_ordering装饰器有助于减少样板。 total_ordering需要实现__eq__和其余方法之一,新建一个sort_coins.py文件,如下:

from typing import NamedTuplefrom functools import total_ordering# a gold coin equals to two silver and six bronze coinsclass Coin(NamedTuple):    rank: str@total_orderingclass Pouch:    def __init__(self):        self.bag = []    def add(self, coin):        self.bag.append(coin)    def __eq__(self, other):        val1, val2 = self.__evaluate(other)        if val1 == val2:            return True        else:            return False            def __lt__(self, other):        val1, val2 = self.__evaluate(other)        if val1 < val2:            return True        else:            return False    def __str__(self):        return f'Pouch with: {self.bag}'    def __evaluate(self, other):        val1 = 0        val2 = 0        for coin in self.bag:            if coin.rank == 'g':                val1 += 6            if coin.rank == 's':                val1 += 3            if coin.rank == 'b':                val1 += 1        for coin in other.bag:            if coin.rank == 'g':                val2 += 6            if coin.rank == 's':                val2 += 3            if coin.rank == 'b':                val2 += 1        return val1, val2def create_pouches():    p1 = Pouch()    p1.add(Coin('g'))    p1.add(Coin('b'))    p1.add(Coin('s'))    p2 = Pouch()    p2.add(Coin('g'))    p2.add(Coin('s'))    p3 = Pouch()    p3.add(Coin('b'))    p3.add(Coin('s'))    p3.add(Coin('s'))    p4 = Pouch()    p4.add(Coin('b'))    p4.add(Coin('s'))    p5 = Pouch()    p5.add(Coin('g'))    p5.add(Coin('s'))    p5.add(Coin('s'))    p5.add(Coin('b'))    p5.add(Coin('b'))    p5.add(Coin('b'))    p6 = Pouch()    p6.add(Coin('b'))    p6.add(Coin('b'))        p6.add(Coin('b'))        p6.add(Coin('b'))        p6.add(Coin('b'))       p7 = Pouch()    p7.add(Coin('g'))    p8 = Pouch()    p8.add(Coin('g'))    p8.add(Coin('g'))    p8.add(Coin('s'))    bag = [p1, p2, p3, p4, p5, p6, p7, p8]    return bagbag = create_pouches()bag.sort()for e in bag:    print(e)

输出结果为:

Pouch with: [Coin(rank='b'), Coin(rank='s')]Pouch with: [Coin(rank='b'), Coin(rank='b'), Coin(rank='b'), Coin(rank='b'), Coin(rank='b')]Pouch with: [Coin(rank='g')]Pouch with: [Coin(rank='b'), Coin(rank='s'), Coin(rank='s')]Pouch with: [Coin(rank='g'), Coin(rank='s')]Pouch with: [Coin(rank='g'), Coin(rank='b'), Coin(rank='s')]Pouch with: [Coin(rank='g'), Coin(rank='s'), Coin(rank='s'), Coin(rank='b'), Coin(rank='b'), Coin(rank='b')]Pouch with: [Coin(rank='g'), Coin(rank='g'), Coin(rank='s')]

这一小节的知识点有点多,大家不妨慢慢消化一下,哪里不懂的可以查下资料或者私聊我都是可以的,写作不容易,比较费脑子,写出来的东西希望对大家有用,不然的话,那就是无用功啊

标签: #python二维list排序 #pythonlist数字排序 #python怎么对字典进行排序 #如何用python排序并只输出前几个 #pythonlist排序