1. 程式人生 > 其它 >python排序sort&sorted

python排序sort&sorted

技術標籤:python列表排序sortsorted

1.語法詳解

#list內建sort()方法用來排序
list.sort(key=None, reverse=False)
#全域性sorted()方法來對可迭代的序列排序生成新的序列
sorted(iterable, key=None, reverse=False)

key :主要是用來進行比較的元素,只有一個引數,具體的函式的引數就是取自於可迭代物件中,指定可迭代物件中的一個元素來進行排序。
reverse: 排序規則,reverse = True 降序, reverse = False 升序(預設)。

2.排序基礎

1.sorted

mylist = [4,6,0,1,2,3]
sort_list = sorted(mylist)
print(sort_list)    #排序後的序列:[0, 1, 2, 3, 4, 6]
print(mylist)       #原序列:[4, 6, 0, 1, 2, 3]

2.sort

mylist = [4,6,0,1,2,3]
mylist.sort()
print(mylist)    #排序後改變了原序列:[0, 1, 2, 3, 4, 6]

不同點
list.sort()方法僅被定義在list中,相反地sorted()方法對所有的可迭代序列都有效。

#dict
new_list =
sorted({1: 'D', 2: 'B', 4: 'B', 3: 'E', 5: 'A'}) print(new_list) #[1, 2, 3, 4, 5] #tuple new_list = sorted((4,5,0,1,2,6)) print(new_list) #[0, 1, 2, 4, 5, 6]

3.升序和降序

mylist = [4,5,0,1,2,6]
mylist.sort()   #預設reverse=False
print(mylist)   #[0, 1, 2, 4, 5, 6]
mylist.sort(reverse=True)
print(mylist)   #[6, 5, 4, 2, 1, 0]

4.key引數/函式

list.sort()和sorted()函式增加了key引數來指定一個函式,此函式將在每個元素比較前被呼叫

1.通過key指定的函式來忽略字串的大小寫

ll1 = sorted("This is a test string from Andrew".split(), key=str.lower)
print(ll1)      #['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
ll2 = sorted("This is a test string from Andrew".split())
print(ll2)      #['Andrew', 'This', 'a', 'from', 'is', 'string', 'test']

2.根據特定屬性排序
key引數的值為一個函式,此函式只有一個引數且返回一個值用來進行比較

student_tuples = [
        ('john', 'A', 15),
        ('jane', 'B', 10),
        ('dave', 'B', 12),
]
#結合lambda, 這裡是按照每個元組的第三個元素來排序
student_tuples.sort(key=lambda s: s[2])
print(student_tuples)       #[('jane', 'B', 10), ('dave', 'B', 12), ('john', 'A', 15)]

3.根據物件的屬性進行物件排序

class Student:
    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age
    def __repr__(self):
        return repr((self.name, self.grade, self.age))
    

student_objects = [
        Student('john', 'A', 15),
        Student('jane', 'B', 12),
        Student('dave', 'B', 10),
]

#通過物件的屬性age排序
student_objects.sort(key=lambda student: student.age)
print(student_objects)      #[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

說明:
repr例項1

#關於__repr__, __str__是作為字串列印時呼叫
#可能的表示出一個物件來源的類以及繼承關係
#如果不新增方法__repr__
print(student_objects[0])			
#<__main__.Student object at 0x000002BA66EDD6A0>

#新增後
('dave', 'B', 10)

repr例項2

import datetime
today = datetime.datetime.now()
print(str(today))
# 2020-12-16 13:46:30.599880
print(repr(today))
# datetime.datetime(2020, 12, 16, 13, 46, 30, 599880)

4.多個排序規則
內建方法:

# import re
# 
student = [{
        'sid': 1,
        'high':176,
        'weight':61
    },
    {
        'sid': 2,
        'high':176,
        'weight':59
    },
    {
        'sid': 3,
        'high':165,
        'weight':62
    },
    {
        'sid': 4,
        'high':180,
        'weight':75
    },
    {
        'sid': 5,
        'high':175,
        'weight':61
    },
    {
        'sid': 6,
        'high':178,
        'weight':61
    },
    {
        'sid': 7,
        'high':165,
        'weight':64
    },
    {
        'sid': 8,
        'high':171,
        'weight':68
    },
    {
        'sid': 9,
        'high':171,
        'weight':68
    },
    ]

#先按照學生的身高排序,如果身高相同,則按照體重排序
student.sort(key=lambda k: (k["high"],k["weight"]))


演算法實現
學校舉行運動會,學生們按編號(1,2,3……n)進行標識,現需要按照身高由低到高排列,對身高相同的人,按體重由輕到重排列;對於身高體重都相同的人,維持原有的編號順序關係。請輸出排列後的學生編號

def test():
    n = int(input())
    high = input().split(" ")
    weight = input().split(" ")
    data = []
    for i in range(1,n+1):
        info = {"id":i,
                "high":int(high[i-1]),
                "weight":int(weight[i-1])}
        data.append(info)
    
    #氣泡排序
    for i in range(len(data)):
        for j in range(i+1,len(data)):
            if data[j-1]["high"]>data[j]["high"]:
                data[j-1],data[j] = data[j],data[j-1]
            if data[j-1]["high"]==data[j]["high"]:
                if data[j-1]["weight"]>data[j]["weight"]:
                    data[j-1],data[j] = data[j],data[j-1]
    for info in data:
        print(info["id"], end=" ")
test()
#輸入
5
172 180 178 172 177
65 70 62 68 71
#輸出
1 4 5 3 2