Python语法记录

list

  • 创建列表,获取长度
    1
    2
    3
    4
    5
    6
    7
    # 已知元素
    mylist = [1,2,3,4]
    # 未知元素
    mylist = []
    mylist.append(1)
    # 获取长度
    length = len(mylist)
  • 对list所有元素执行统一操作
    1
    2
    3
    4
    # 不想写循环的话,且不想改变原列表元素
    test = [1,2,3,4,5] # [1, 2, 3, 4, 5]
    test1 = [x+1 for x in test] # [2, 3, 4, 5, 6]
    test2 = list(map(lambda x:x+1, test)) # [2, 3, 4, 5, 6]

    array

    array数组在python中是不可改变的
  • 创建array
    1
    2
    3
    4
    5
    6
    import numpy as np
    test = np.array([1,2,3,4,5])
    # 获取形状
    shape = test.shape
    #获取部分元素
    part = test[2:4]

Dict

  • 获取字典的key值
    1
    2
    3
    4
    5
    6
    for key in dict:
    print(key)
    for i, key in enumerate(dict):
    print(f"the {i} key:", key)
    for key in dict.keys():
    print(key)
  • 获取字典键值对
    1
    2
    3
    4
    5
    # 输出为数组,例如('key','value')
    for kv in dict.items():
    print(kv)
    for key,value in dict.items():
    print(f"{key}:{value}")

sort & sorted

  • sort
    list内置的sort()函数(只适用于list),本身不会返回新的list,会改变原先的list的顺序(节省空间,提高效率)
    1
    2
    my_list = [3, 5, 1, 4, 2]
    my_list.sort() # [1, 2, 3, 4, 5]
  • sorted
    sorted()函数适用于任意可以迭代的对象排序,不会改变原对象,返回一个新的可迭代对象
    1
    2
    my_list = [3, 5, 1, 4, 2]
    result = sorted(my_list) # [1, 2, 3, 4, 5]

    cv2

  • cv2.resize()
    要求size为integer,否则报错
    1
    cv2img = cv2.resize(cv2img, (size1, size2))

使用f-string保留小数点位数

参考文章

  • Python:使用f-string保留小数点位数

  • 格式

    1
    f"{num:xxx}"

    上面xxx的格式如下:

    格式 说明
    width 整数width指定宽度
    0width 整数width指定宽度,0表示最高位用0补足宽度
    width.precision 整数width指定宽度,整数precision表示精度(保留小数点后几位小数)
  • 实例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    a = 123.456

    # 只指定widthc
    >>> f"{a:10}"
    '123.456'

    # 指定0width
    >>> f"{a:010}"
    '000123.456'

    # 使用width.precision
    >>> f"{a:10.1f}"
    '123.5'
    >>> f"{a:.2f}"
    '123.46'