Python 在问答频道中刷题积累到的小技巧(七)

x33g5p2x  于2022-06-27 转载在 Python  
字(2.9k)|赞(0)|评价(0)|浏览(421)

  1. max(),min()函数的key参数应用

快速找出众数:

>>> import random
>>> r = [rnd(1,9) for _ in range(20)]
>>> r
[3, 3, 5, 9, 1, 7, 4, 1, 1, 9, 6, 8, 3, 9, 8, 8, 6, 4, 6, 6]
>>> max(r, key=r.count)
6

找最短密码(首个匹配到的):

>>> from random import choices, randint as rnd
>>> s = ''.join((map(chr,[*range(ord('A'),ord('Z')+1),*range(ord('a'),ord('z')+1),*range(ord('0'),ord('9')+1),ord('-')])))
>>> p = [''.join(choices(s,k=rnd(3,10))) for _ in range(10)]
>>> p
['fiKYKBl', 'HZjwZUGg', 'pUaKkKtrE8', '2qet35e1Q', 'is34n11F', 'Jxed96', '9K8TOE', 'sqymdfx', 'SRjuq', 'J9TBu']
>>> min(p, key=lambda x:len(x))
'SRjuq'

位数最多、最少的整数 :(首个匹配到的数,与最大值、最小值未必相等)

>>> from random import choices, randint as rnd
>>> n = [int(''.join(map(str,choices(range(10),k=rnd(3,10))))) for _ in range(10)]
>>> n
[9345447, 1030757133, 8630, 293949, 497, 1206340275, 172, 950651, 983, 138]
>>> max(n, key=lambda x:len(str(x)))
1030757133
>>> min(n, key=lambda x:len(str(x)))
497
>>>
>>> max(n)
1206340275
>>> min(n)
138
  1. 列表任意指定长度的分组
def splitlist(lst,*group):
    res,lst = [],lst[:]
    for i in group:
        t = []
        for _ in range(i):
            if lst: t.append(lst.pop(0))
            else: break
        if t: res.append(t)
    if lst: res.append(lst)
    return res

a = [1,2,3,4,5,6,7,10,11,12,20,21,23]
print(splitlist(a,8,4,2,1))
# [[1, 2, 3, 4, 5, 6, 7, 10], [11, 12, 20, 21], [23]]
print(splitlist(a,7,3,2,1))
# [[1, 2, 3, 4, 5, 6, 7], [10, 11, 12], [20, 21], [23]]
print(splitlist(a,7,3,2,2))
# [[1, 2, 3, 4, 5, 6, 7], [10, 11, 12], [20, 21], [23]]
print(splitlist(a,7,3,2))
# [[1, 2, 3, 4, 5, 6, 7], [10, 11, 12], [20, 21], [23]]
print(splitlist(a,7,3))
# [[1, 2, 3, 4, 5, 6, 7], [10, 11, 12], [20, 21, 23]]
print(splitlist(a,7,2,2,5))
# [[1, 2, 3, 4, 5, 6, 7], [10, 11], [12, 20], [21, 23]]
  1. 用numpy解多元一次方程组
import numpy as np
A = [[1,-2,1],[0,2,-8],[-4,5,9]]     # 系数矩阵
B = [0,8,-9]                         # 常数矩阵
x,y,z = np.linalg.inv(A).dot(B)      # 求方程组的解
print(f'x={x}, y={y}, z={z}')        # 默认它有且只有一组解,不展开讨论
  1. 应用字典同时返回两数的和差积商余
def exp(a,b):
    choice = {	1: lambda x, y: x + y,
		        2: lambda x, y: x - y,
		        3: lambda x, y: x * y,
		        4: lambda x, y: x // y,
		        5: lambda x, y: x % y	}
    return tuple(choice[i+1](a,b) for i in range(5))

print(exp(8,3))     # (11, 5, 24, 2, 2)
print(exp(5,6)[2])  # 30
  1. 多种方法取出某字母开头的元素
>>> s = ['foot','head','Face','Hair','nose','Mouth','finger','ear']
>>> [w for w in s if w[0].lower()=='f']
['foot', 'Face', 'finger']
>>> [w for w in s if w[0] in ('f','F')]
['foot', 'Face', 'finger']
>>> [w for w in s if w.startswith(('F','f'))]
['foot', 'Face', 'finger']
  1. 输入一个整数,输错不会异常退出
n = ''
while not n.isnumeric(): n = input('输入一个非负整数:')
n = int(n)
n = ''
while not (n.isnumeric() or len(n) and n[0]=='-' and n[1:].isnumeric()):
    n = input('输入一个整数:')
n = int(n)

【相关阅读】

Python 在问答频道中刷题积累到的小技巧(一)https://hannyang.blog.csdn.net/article/details/124935045

Python 在问答频道中刷题积累到的小技巧(二)https://hannyang.blog.csdn.net/article/details/125026881

Python 在问答频道中刷题积累到的小技巧(三)
https://hannyang.blog.csdn.net/article/details/125058178

Python 在问答频道中刷题积累到的小技巧(四)
https://hannyang.blog.csdn.net/article/details/125211774

Python 在问答频道中刷题积累到的小技巧(五)https://hannyang.blog.csdn.net/article/details/125270812

Python 在问答频道中刷题积累到的小技巧(六)
https://hannyang.blog.csdn.net/article/details/125339202

相关文章