python常用算法操作汇总

1.创建二维数组

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

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

正确姿势

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

2.获取列表元素的下标

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

数组去重

lst = [2,2,3,4,4]
print(list(set(lst))) # [2, 3, 4]
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)

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)]
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)

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

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

6.最大最小安全值

print(float('inf'))
print(float('-inf'))

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)

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]
# 最大堆

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]

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)

此处代码表示什么意思?
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__

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值