• python常用操作汇总


    1.创建二维数组

    python创建三行三列的二维数组,下面方法是错误的,因为是浅拷贝

    lst1 = [0] * 3
    lst2 = [lst1] * 3
    lst2[1][1] = 2
    print(lst2) # [[0, 2, 0], [0, 2, 0], [0, 2, 0]]
    
    • 1
    • 2
    • 3
    • 4

    正确姿势

    lst = [[0 for j in range(3)] for i in range(3)]
    lst[1][1] = 2
    
    • 1
    • 2

    2.获取列表元素的下标

    lst = [1,2,3,4,5]
    pos = lst.index(3)
    print(pos) # 2
    
    • 1
    • 2
    • 3

    数组去重

    lst = [2,2,3,4,4]
    print(list(set(lst))) # [2, 3, 4]
    
    • 1
    • 2
    dic = {}
    # 增
    dic[1] = '苏'
    dic[2] = '苏1'
    dic[3] = '苏2'
    dic[4] = '你'
    print(dic) # {1: '苏', 2: '苏1', 3: '苏2', 4: '你'}
    # 删
    del dic[1]
    print(dic) # {2: 'su1', 3: 'su2', 4: '你'}
    # 改
    dic[2] = '张'
    # 查
    print(dic[2]) # 张
    print(dic.get(3, None)) # 苏2
    print(dic.get(5, None)) # None
    print(2 in dic) # True
    
    print(dic.keys())
    print(dic.values())
    
    for i in enumerate(dic):
        print(i)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    3.对字典排序

    # 先认识字典的基本操作
    l1 = ['c','ab', 'a', 'd','e']
    l2 = [1, 3, 1, 2, 4]
    dic = dict(zip(l1, l2))
    print(dic) # {'c': 1, 'ab': 3, 'a': 1, 'd': 2, 'e': 4}
    print(dic.items()) # dict_items([('c', 1), ('ab', 3), ('a', 1), ('d', 2), ('e', 4)])
    print(list(dic.items())) # [('c', 1), ('ab', 3), ('a', 1), ('d', 2), ('e', 4)]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    l1 = ['c','ab', 'a', 'd','e']
    l2 = [1, 3, 1, 2, 4]
    lst = list(zip(l1, l2))
    # 表示按值进行排序
    lst1 = sorted(lst, key=lambda x: x[1])
    lst2 = sorted(lst, key=lambda x: -x[1])
    print("列表按值排序:", lst1)
    print("列表按值倒序", lst2)
    n = len(lst1)
    # 从小到大排序,如果列表元素的一个值相等,比较第二个值字符串大小,越小越往前。
    for i in range(n-1):
        if lst1[i][1] == lst1[i+1][1] and lst1[i][0] > lst1[i+1][0]:
            lst1[i],lst1[i+1] = lst1[i+1],lst1[i]
    print("值相等,按字母大小排序:",lst1)
    # 表示按键进行排序
    lst2 = sorted(lst, key=lambda x: x[0])
    print(lst2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    4.正则表达式

    import re
    s="This is a number 234-235-22-423"
    # 非贪婪模式:适可而止
    r1=re.match(".+?(\d+-\d+-\d+-\d+)", s)
    # 贪婪模式:得寸进尺
    r2=re.match(".+(\d+-\d+-\d+-\d+)", s)
    print(r1.group(1)) # 234-235-22-423
    print(r2.group(1)) # 4-235-22-423
    
    s="aaa123456"
    r1 = re.match("aaa(\d+?)", s)
    r2 = re.match("aaa(\d+)", s)
    print(r1.group(1)) # 1
    print(r2.group(1)) # 123456
    
    
    s="aaa123456bbb"
    r1 = re.match("aaa(\d+?)b", s)
    r2 = re.match("aaa(\d+)b", s)
    print(r1.group(1)) # 123456
    print(r2.group(1)) # 123456
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    5.进制转换

    # 2、8、16转十进制
    a = '110'
    print(int(a, 2)) # 6
    b = '061'
    print(int(b, 8)) # 49
    c = 'ee'
    print(int(c, 16)) # 238
    
    # 十进制转2、8、16进制
    d = 12
    print(bin(d)) # 0b1100
    print(oct(d)) # 0o14
    print(hex(d)) # 0xc
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    6.最大最小安全值

    print(float('inf'))
    print(float('-inf'))
    
    • 1
    • 2

    js的最大安全值:Math.max_safe_integer

    bisect用法

    # 二分插入源码:不断缩小范围。nums要经过升序排序
    def search(self, nums, l, r, target):
        # 二分插入
        if (nums[r] <= target):
            return r + 1
    
        while l < r: # 左闭右开 → 则
            mid = (l + r) // 2
            if (nums[mid] > target):
                r = mid
            else:
                l = mid + 1
    
        return l
    
    # 语法
    # bisect(list, num)
    # bisect_left(list, num)
    # bisect_right(list, num)
    # 用途:1、查找的数不在数组中 2、查找的数在数组中且只有一个 3、查找的数在数组中并且有多个
    
    # 查找的数不在数组中
    import bisect
    list1 = [1,3,5,7,9,11,11,11,11,11,13]
    a = bisect.bisect(list1,6)
    b = bisect.bisect_left(list1,6)
    c = bisect.bisect_right(list1,6)
    print(a,b,c)
    # 输出为 3,3,3
    
    # 查找的数在数组中并且有多个
    import bisect
    list1 = [1,3,5,7,9,11,11,11,11,11,13]
    a = bisect.bisect(list1,9)
    b = bisect.bisect_left(list1,9)
    c = bisect.bisect_right(list1,9)
    print(a,b,c)
    # 输出 5,4,5
    
    # 二分插入函数bisect.insort()
    list2 = []
    bisect.insort(list2,5)
    print(list2)
    bisect.insort(list2,6)
    print(list2)
    bisect.insort(list2,1)
    print(list2)
    bisect.insort(list2,1)
    print(list2)
    bisect.insort(list2,10)
    print(list2)
    bisect.insort(list2,0)
    print(list2)
    bisect.insort(list2,3)
    print(list2)
    bisect.insort(list2,2)
    print(list2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    7.堆(heapq)的使用

    堆可以快速获取当前列表最小值。

    # 最小堆
    import heapq
    
    minHeap = [1,5,8,9,6,3]
    heapq.heapify(minHeap) # [1, 5, 3, 9, 6, 8]
    heapq.heappush(minHeap, 0) # [0, 5, 1, 9, 6, 8, 3]
    minNum = heapq.heappop(minHeap) # minNum=0,minHeap=[1, 5, 3, 9, 6, 8]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    # 最大堆
    
    import heapq
    maxHeap = [1, 2, 3, 4, 5]
    maxHeap = [-x for x in maxHeap]
    heapq.heapify(maxHeap) #  [-5, -4, -3, -1, -2]
    maxHeap = [-x for x in maxHeap] # [5, 4, 3, 1, 2]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    8.比较两个到三个数以上使用对象方法

    # 录取原则:技面分数高先录取,若技面分数相同则机考分数高先录取,若机考分数也相同则按最小编号录取。
    # 问题:那如何同时比较三个数?如何实现类型比较字符串 "ABC" < "CbA"方法? → 解答:单个数比较直接使用基本数据类型比较,多个数比较则需使用类
    class Candidate:
        def __init__(self, id, progm_score, tech_score):
            self.id = id
            self.prog_score = progm_score
            self.tech_score = tech_score
            self.priority = (self.tech_score, self.prog_score, self.id)
    
        def __lt__(self, other):
            return self.priority > other.priority
    
    def print_candidates(candidates):
        for i in candidates:
            print(i.tech_score, i.prog_score)
        print()
    
    candidateAbilities = [
        [250, 200],
        [260, 290],
        [250, 300],
        [300, 290],
        [260, 290],
        [260, 290]
    ]
    candidate_abilities = [Candidate(i, *el) for i,el in enumerate(candidateAbilities)]
    
    candidate_abilities.sort()
    print_candidates(candidate_abilities)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    此处代码表示什么意思?
    def lt(self, other):
    return self.priority > other.priority

    举个例子,假设有两个Candidate对象,c1和c2,它们的属性如下:
    c1.id = 1 c1.progm_score = 80 c1.tech_score = 90 c1.priority = (90, 80, 1)
    c2.id = 2 c2.progm_score = 85 c2.tech_score = 85 c2.priority = (85, 85, 2)

    如果我们执行c1 < c2,就相当于比较c1.priority和c2.priority,即(90, 80, 1)和(85, 85, 2)。因为c1的tech_score比c2的tech_score高,所以c1被认为更小,所以c1 < c2返回True。注意,这里的__lt__方法是用了反向的逻辑,即如果self.priority > other.priority,就返回True,这是为了让tech_score和progm_score越高的对象越小,而不是越大。相应的,比较更大值使用__gt__

  • 相关阅读:
    架构与思维:微服务架构的思想本质
    LeetCode刷题第7周小结
    信息化发展65
    环境配置 | 图文VS2022配置OpenCV,Dlib
    NLA自然语言分析实现数据分析零门槛
    2021年软件测试面试题大全
    HummerRisk 快速入门教程
    【C++面向对象程序设计】CH5 继承与派生
    【这款神器可以有】3DMAX一键墙体门洞窗洞插件使用教程
    Ubuntu server 24 (Linux) 安装lua + 卸载软件
  • 原文地址:https://blog.csdn.net/weixin_40981660/article/details/134094156