• Python3 学习笔记


    一. 内置函数

    1. sorted()

    对所有可迭代的对象进行排序操作,返回重新排序的列表。

    sorted(iterable, key=None, reverse=False)

    • iterable – 可迭代对象。
    • key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
    • reverse – 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
    a = [5, 2, 3, 1, 4]
    x1 = sorted(a)
    # [1, 2, 3, 4, 5] # 默认为升序
    
    x2 = sorted(a, reverse=True)
    # [5, 4, 3, 2, 1]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    实例,对奖牌榜进行排序

    import numpy as np
    
    s = "德国 10 11 16\n意大利 10 10 20\n荷兰 10 12 14\n法国 10 12 11\n英国 22 21 22\n中国 38 32 18\n日本 27 14 17\n美国 39 41 33\n俄罗斯奥委会 20 28 23\n澳大利亚 17 7 22\n匈牙利 6 7 7\n加拿大 7 6 11\n古巴 7 3 5\n巴西 7 6 8\n新西兰 7 6 7"
    stodata = s.split('\n', -1) # 分割数组
    
    # 使用sorted
    para = {}
    for line in range(len(stodata)):
        # 每一行数据
        data = stodata[line].split(' ') # 分割数组
        print(data)
    
        # 把奖牌数重新组合为一个数组,组装数据结构para={'China': [], 'Russia': []}
        para[data[0]] = [int(i) for i in data[1:]]
    
    # 开始排序(x[1]代表奖牌数目, x[0]代表国家),以奖牌总数降序排列
    new_para = sorted(para.items(), key=lambda x: (x[1], x[0]), reverse=True) # items() 历遍数组
    
    # 分割线
    print('\n', np.char.center('分割线', 50, fillchar='*'), '\n')
    
    c = [] # 排序后的国家名数组
    for i in new_para:
        c.append((i[0]))
    for j in range(15):
        print(f'{j+1}  {c[j]}')
    
    • 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

    2. print()

    用于打印输出。

    print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

    • objects – 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
    • sep – 用来间隔多个对象,默认值是一个空格。
    • end – 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
    • file – 要写入的文件对象。
    • flush – 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。
    print('aaa''bbb')
    # aaabbb
    
    print('aaa', 'bbb')
    # aaa bbb
    
    print('aaa', 'bbb', sep='.')  # 设置间隔符
    # aaa.bbb
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.1 print() 函数常用用法总结1

    2.1.1 格式化符号

    python 字符串格式化符号(部分)

    符 号描述
    %s格式化字符串
    %d格式化整数
    %u格式化无符号整型
    %f格式化浮点数字,可指定小数点后的精度

    格式化操作符辅助指令(部分)

    符号功能
    *定义宽度或者小数点精度
    -用做左对齐
    +在正数前面显示加号 +
    0显示的数字前面填充 0 而不是默认的空格
    (var)映射变量(字典参数)
    m.n.m 是显示的最小总宽度, n 是小数点后的位数(如果可用的话)

    2.1.2 格式化输出整数

    print('the length of (%s) is %d' % ('runoob', len('runoob')))
    # the length of(runoob) is 6
    
    • 1
    • 2

    2.1.3 格式化输出浮点数(float)

    pi = 3.141592653
    
    print('%10.3f' % pi)  # 字段宽10,精度3
    #  3.142
    
    print('pi = %.*f' % (3, pi))  # 用*从后面的元组中读取字段宽度或精度
    print('pi = %.3f' % pi) # 同上
    # pi = 3.142
    
    print('%010.3f' % pi) # 用0填充空白
    # 000003.142
    
    print('%-10.3f' % pi) # 左对齐,默认右对齐
    # 3.142
    
    print('%+f' % pi) #显示正负号
    # +3.141593
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2.1.4 自动换行

    print() 会自动在行末加上回车,如果不需回车,需设置分隔符 end。

    for i in range(0, 3):
        print(i)
    # 0
    # 1
    # 2
    
    for j in range(0, 3):
        print(j, end=' ')
    # 0 1 2 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2.2 使用大括号 {} 输出变量和字符串2

    first_name = "John"
    last_name = "Doe"
    
    print("Hello {} {}, hope you're well!".format(last_name, first_name))
    # Hello Doe John, hope you're well!
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.3 使用 f-strings 输出变量和字符串2

    与上面方法相比,f-strings 是一种更简洁的字符串格式化方法。
    在引号前加入字符 f ,在要添加变量值的地方添加一组大括号,里面是变量名。

    first_name = "John"
    last_name = "Doe"
    
    print(f"Hello, {first_name}!")
    # Hello, John!
    
    print(f"Hello, {first_name} {last_name}!")
    # Hello, John Doe!
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.4 format() 3

    Python2.6 开始,新增了一种格式化字符串的函数 str.format() ,基本语法是通过 {}: 来代替以前的 %
    format() 函数可以接受不限个数参数,位置可以不按顺序。

    print("{} {}".format("hello", "world"))  # 不设置指定位置,按默认顺序
    # hello world
     
    print("{0} {1}".format("hello", "world"))  # 设置指定位置
    # hello world
     
    print("{1} {0} {1}".format("hello", "world"))  # 设置指定位置
    # world hello world
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    也可以设置参数

    print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
    # 网站名:菜鸟教程, 地址 www.runoob.com
    
    # 通过字典设置参数
    site = {"name": "菜鸟教程", "url": "www.runoob.com"}
    print("网站名:{name}, 地址 {url}".format(**site)) # **代表收集关键字参数
     
    # 通过列表索引设置参数
    my_list = ['菜鸟教程', 'www.runoob.com']
    print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    数字格式化(部分)

    print("{:.2f}".format(3.1415926))
    # 3.14
    
    • 1
    • 2
    数字格式输出描述
    3.1415926{:.2f}3.14保留小数点后两位
    2.71828{:.0f}3不带小数
    5{:0>2d}05数字补零 (填充左边, 宽度为2)
    5{:x<4d}5xxx数字补x (填充右边, 宽度为4)
    1000000{:,}1,000,000以逗号分隔的数字格式
    0.25{:.2%}25.00%百分比格式
    1000000000{:.2e}1.00e+09指数记法
    13{:>10d}  13右对齐 (默认, 宽度为10)
    13{:<10d}13左对齐 (宽度为10)
    13{:^10d} 13中间对齐 (宽度为10)

    二. 使用技巧

    1. 显示 xxx is not callable 错误

    书写不规范,调用了一个错误的变量或者函数,注意不要使用内置函数名作为变量名。

    2. 打印分割线

    import numpy as np
    
    # 分割线
    print('\n', np.char.center('分割线', 50, fillchar='*'), '\n')
    
    • 1
    • 2
    • 3
    • 4

    1. 参考链接 ↩︎

    2. 参考链接 ↩︎ ↩︎

    3. 参考链接 ↩︎

  • 相关阅读:
    彻底理解Java并发:ReentrantLock锁
    小程序的开发之路③
    文心一言 VS 讯飞星火 VS chatgpt (138)-- 算法导论11.4 2题
    Flutter 中点击输入框之外的区域,进行失焦,收起键盘
    IDEA2022用maven创建的Servlet项目
    Day59——Ajax,前后端数据编码格式
    昨天阅读量646
    webpack5基于React+Antd搭建开发和生产环境
    FL Studio 20.9水果编曲软件中文汉化补丁包
    计算机中的进制转换
  • 原文地址:https://blog.csdn.net/gaofei880219/article/details/126300975