• python例题代码


    import numpy as np
    import pandas as pd
    
    • 1
    • 2

    1.替换

    利用np.where(b>30,30,b)

    import numpy as np
    np.random.seed(100)
    a = np.random.uniform(1,50,10)
    print(a)
    b = np.clip(a,a_min=10,a_max=30)
    print(b)
    c = np.where(a<20,20,a)
    c = np.where(b>30,30,b)
    print(c)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2.找局部最大值(极大值)

    利用np.diff(a)和np.sign(b1)

    a = np.array([1, 3, 7, 1, 2, 6, 0, 1])
    b1 = np.diff(a) # 沿着指定轴计算第N维的离散差值
    b2 = np.sign(b1)
    b3 = np.diff(b2)
    
    print(b1)  # [ 2  4 -6  1  4 -6  1] 后一个减前一个的差值
    print(b2)  # [ 1  1 -1  1  1 -1  1]
    print(b3)  # [ 0 -2  2  0 -2  2]
    index = np.where(np.equal(b3, -2))[0] +1
    print(index) # [2 5]
    #返回a中极大值的坐标
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3.删除函数

    def delete(a, *b):
        if type(a) == int:
            a = str(a)
            b = str(b)
        c = a
        for i in b:
            if type(i) == str:
                c = c.replace(i, '')
            if type(i) != str:
                for j in i:
                    c = c.replace(j, '')
        return c
    
    str1 = 'hi everyone!'
    str1_cleared = delete(str1,'e')
    print('str1_cleared:',str1_cleared)   #str1_cleared: hi vryon!
    str2_cleared = delete(str1,'e','y')
    print('str2_cleared:',str2_cleared)   #str2_cleared: hi vron!
    str3_cleared = delete(str1, ['e', 'y'])
    print('str3_cleared:', str3_cleared)   #str3_cleared: hi vron!
    str4_cleared = delete(str1, 'ev')
    print('str1_cleared:',str4_cleared)
    num1 = 1583759348534
    num1_cleared = delete(num1,8,3)
    print('num1_cleared:',num1_cleared)  #num1_cleared: 15759454
    num2_cleared = delete(num1,[8,3])
    print('num2_cleared:',num2_cleared)
    
    • 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

    4.合并数组

    print(np.c_[np.array([1,2]),np.zeros((2,3))])
    #[[1. 0. 0. 0.]
    # [2. 0. 0. 0.]]
    print(np.r_[np.array([1,2]),np.zeros(2)])
    #[1. 2. 0. 0.]
    print(np.array([1,2]))
    #[1 2]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    5.reshape的作用

    import numpy as np
    target = np.arange(8).reshape(2,4)
    print(target.reshape((4,2), order='C'))
    print(target.reshape((4,2), order='F'))
    
    • 1
    • 2
    • 3
    • 4

    6.用函数实现矩阵乘法

    import numpy as np
    m1 = np.random.rand(2,3)
    m2 = np.random.rand(3,4)
    res = np.empty((m1.shape[0],m2.shape[1]))
    print(res)
    for i in range(m1.shape[0]):
        for j in range(m2.shape[1]):
            item = 0
            for k in range(m1.shape[1]):
                item += m1[i][k]*m2[k][j]
            res[i][j] = item
    print((np.abs((m1@m2-res)<1e-15)).all())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    7.更新矩阵

    a = np.array(range(1,10)).reshape(3,3)
    print(a)
    def changejuzheng(a):
        b = np.empty(a.shape)
        for i in range(a.shape[0]):
            for j in range(a.shape[1]):
                item = 0
                for k in range(a.shape[0]):
                    item += 1/a[i][k]
                b[i][j] = a[i][j]*item
        return b
    print(changejuzheng(a))
    #法二,同样能实现上面功能
    b = a*(1/a).sum(1).reshape(-1,1)
    print(b)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    8.递增序列的最大个数

    f = lambda x:np.diff(np.nonzero(np.r_[1,np.diff(x)!=1,1]))
    print(f([1,2,5,6,7]))
    
    • 1
    • 2

    9.rolling滑动窗口

    import pandas as pd
    # 导入 pandas
    index = pd.date_range('2022-01-01',periods=6)
    #创建日期序列
    data = pd.DataFrame(np.arange(len(index)),index=index,columns=['test'])
    #创建简单的pd.DataFrame
    print(data)
    #打印data
    data['sum'] = data.test.rolling(3).sum()
    #移动3个值,进行求和
    data['mean'] = data.test.rolling(3).mean()
    #移动3个值,进行求平均数
    data['mean1'] = data.test.rolling(3,min_periods=2).mean()
    print(data)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    10.累计窗口

    s = pd.Series([1, 3, 6, 10])
    print(s.expanding().sum())
    print(s.expanding().mean())
    
    • 1
    • 2
    • 3

    11.

    print(np.nan != np.nan)   #True
    print(np.nan is np.nan)    #True
    
    • 1
    • 2

    12.1-100的和

    print(sum(range(101)))
    
    • 1

    13,如何在函数内容修改全局变量 —global

    5个python标准库:os与操作系统相关联的库,sys命令行参数 ,re正则匹配,math 数学运算 ,datetime处理日期时间

    python2与python3的range(100)区别:
    python返回列表
    python3返回迭代器,节约内存

    什么样的语言能够用装饰器:函数可以作为参数传递的语言,可以使用装饰器

    python内建函数类型:整型int 布尔型bool 字符串str 列表list 元组tuple 字典dict

    python2与python3的区别?

    1。python3输出print(‘hi’) ,python2输出可以print(‘hi’)或者print ‘hi’ 去掉括号使用一个空格
    2. python2的range(1,10)返回列表,python3返回迭代器,节约空间
    3.python2使用ascii编码,python3使用utf-8编码
    4。python2中unicode表示字符串序列,str表示字节序列
    python3中str表示字符串序列,byte表示字节序列
    5.python2中为正常显示中文,引入coding声明,python3中不需要
    6,python 中raw_input(),python3中input()函数

    不可变数据类型:数值型,字符串型string,元组tuple
    可变数据类型:列表list 字典dict

    14,字典删除键del和合并键update

    dic = {'name':'sz','num':123}
    del dic['name']
    print(dic)
    dic2 = {'sex':'male'}
    dic.update(dic2)   #合并到了dic自身上面
    print(dic)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    15,列表去重,利用集合的特点

    a = [11,12,13,14,15,11,13]
    b = set(a)
    a = list(b)
    print(a)
    
    • 1
    • 2
    • 3
    • 4

    16,列表平方,并取出大于10的值 map(fan,list)

    list = [1,2,3,4,5]
    def fn(x):
        return x**2
    res = map(fn,list)
    res = [i for i in res if i>10]
    print(res)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    17,随机整数、小数、0-1间小数

    import random
    a = random.randint(1,5)  #1-5区间内的随机整数,产生一个
    b = random.random()      #0-1间的随机小数,产生一个
    c = np.random.randn(2)   #返回2个标准正太分布数值,理论上是(负无穷,正无穷)。实际上是在数值0附近徘徊
    print(a,b,c)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    18,字典根据键从小到大排序

    dict={"name":"zs","age":18,"city":"深圳","tel":"1362626627"}
    print(dict.items()) #dict_items([('name', 'zs'), ('age', 18), ...
    list = sorted(dict.items(),key=lambda i:i[0],reverse=False) #i[0]是键,i[1]是值
    print('sorted根据字典键排序',list)  #返回的是列表
    new_dict = {} #改成字典类型
    for i in list:
        new_dict[i[0]]=i[1]
    print(new_dict)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    19,统计字符串中每个单词出现的次数

    from collections import Counter
    a = "kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h"
    res = Counter(a)
    print(res)  #Counter({'l': 9, ';': 6, 'h': 6, 'f': 5, ..
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    20,字符串a = “not 404 found 张三 99 深圳”,每个词中间是空格,用正则过滤掉英文和数字,最终输出"张三 深圳"?

    import re
    a = 'not 404 found 张三 99 深圳'
    list = a.split(' ')  #用空格进行分割
    print(list)
    res = re.findall('\d+|[a-zA-Z]+',a)  #res是a中数子或者字符部分
    #加上匹配小数:res1 = re.findall('\d+\.?\d*|[a-zA-Z]+',a)
    for i in res:
        if i in list:
            list.remove(i)
    new_str = ' '.join(list)
    print(res)
    print(new_str)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    21,求出列表所有奇数并构造新列表a = [1,2,3,4,5,6,7,8,9,10]

    a = [1,2,3,4,5,6,7,8,9,10]
    def  fn(a):
        return a%2 == 1
    newa = filter(fn,a)
    print(newa)  #没有输出
    newa = [i for i in newa]   #改为列表形式
    print(newa)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    22,列表推导式求列表所有奇数

    a = [1,2,3,4,5,6,7,8,9,10]
    res = [i for i in a if i%2 ==1]
    print(res)
    
    • 1
    • 2
    • 3

    23,合并两个列表

    list1 = [1,2,3,7]
    list2 = [2,3,4,6]
    list1.extend(list2)  #把list2添加到list1上
    print(list1)
    
    • 1
    • 2
    • 3
    • 4

    24,删除文件

    python: os.remove(文件名)
    linux : rm 文件名

    25,日期

    import datetime
    a = str(datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S'))+' 星期:'+str(datetime.datetime.now().isoweekday())
    print(a)
    #datetime.datetime.now()获得当前时间
    #.isoweekday()返回星期几
    
    • 1
    • 2
    • 3
    • 4
    • 5

    26,提高python运行效率的方法

    1,使用生成器,因为可以节约大量内存
    2,循环代码优化,避免过多重复代码的执行
    3,核心模块用Cython PyPy等,提高效率
    4,多进程,多线程,协程
    5,多个if elif条件判断,可以把最有可能先发生的条件放在前面写,这样可以减少程序判断的次数

  • 相关阅读:
    抓包工具charles修改请求和返回数据
    【专用名词的离线语音识别在2024年底的解决方法调查-会议签到的补充】
    334 - 线程通信问题
    代码随想录算法训练营第三十五天丨 贪心算法part06
    8个Tips、16种应用场景电子邮件写作模板,提高外贸邮件回复率!
    【Solidity】智能合约案例——②供应链金融合约
    剖析虚幻渲染体系(16)- 图形驱动的秘密
    【2023秋招】杭州游卡开发岗笔试AK
    《HelloGitHub》第 91 期
    OpenCV自学笔记二十三:K近邻算法
  • 原文地址:https://blog.csdn.net/Sun123234/article/details/126475783