Python Tricks

本文最后更新于:May 7, 2023 pm

列表生成式

将两个嵌套for循环写成一个列表生成式,如 有一个嵌套列表,a=[[1,2],[3,4],[5,6]],要提取列表里的每一个元素

  • for循环处理

    1
    2
    3
    4
    for i in a:
    for j in i:
    print(j)
    # output: [1, 2, 3, 4, 5, 6]
  • 列表生成式

    1
    2
    3
    b = [j for i in a for j in i]  # 注意两个for的顺序
    print(b)
    # output: [1, 2, 3, 4, 5, 6]

格式化

1
2
3
4
5
6
7
8
9
10
print('{0:03}'.format(1))
# output: 001

# 字符串中数字左边补0, 0>2表示数据总显示宽度为2,以0补齐
print('{:0>2d}'.format(3))
# output: 03

# 也可以补齐其它数字,例如8,输出总宽度为5
print('{:8>5d}'.format(3))
# output: 88883

Python Tricks
https://cgabc.xyz/posts/ed67cc57/
Author
Gavin Gao
Posted on
August 2, 2018
Licensed under