Python高级技巧: To Be More Pythonic!

1. zip()函数


if __name__ == '__main__':

    L1 = [1, 2, 3, 4]
    L2 = ['a', 'b', 'c', 'd']
    for z in zip(L1, L2):   # zip关键字将两个list对应起来,组成类似于(key, value)的tuple
        print(z)

    L1 = [1, 2, 3, 4]
    L2 = ['a', 'b', 'c', 'd', 'e']
    print('###')
    for z in zip(L1, L2):
        print(z)

    print('###')
    print(zip(L1, L2))
    print(list(zip(L1, L2)))    # zip的结果可以转化为list
    print(dict(zip(L1, L2)))    # 也可以转化为dict

运行结果为:

Python高级技巧: To Be More Pythonic!_第1张图片

 

2. enumerate()函数

if __name__ == '__main__':

    s = 'ten_sory'
    s = enumerate(s)    # 对应到一个(key, value)组成的tuple

    for x in s:
        print(x, end=' ')
    print()

    print(s)
    print(list(s))  # 不可转化为list
    print(dict(s))  # 或dict

运行结果为:

Python高级技巧: To Be More Pythonic!_第2张图片

 

3. 两个变量交换值

if __name__ == '__main__':
    a = 'I am a boy!'
    b = 2333
    print(a, ' ', b)
    a, b = b, a     # 交换值
    print(a, ' ', b)

运行结果为:

 

4. list拷贝

if __name__ == '__main__':
    L = list(range(0, 10))

    L_1 = L[:]  # 不用担心引用传递的问题了
    print('L_1: ', L_1)
    L_1[1] = 1111 # 仅仅改变自己,不改变L
    print('L_1: ', L_1)
    print('L..: ', L)

    print('################')
    L_2 = L
    print('L_2: ', L_2)
    L_2[1] = 111    # 会修改L的值
    print('L_2: ', L_2)
    print('L..: ', L)

运行结果为:

Python高级技巧: To Be More Pythonic!_第3张图片

 

5. 列表合并

if __name__ == '__main__':
    L = [[1, 2], [4, 5, 6], [7]]
    sum_L = sum(L, [])  # 将二维数组压平的技巧
    print(sum_L)

运行结果为:

 

6. 列表反转

if __name__ == '__main__':
    L = list(range(0, 10))
    print(L)
    r_L = L[::-1]   # 逆序L
    print(r_L)

运行结果为:

 

7. 一行的if-else语句判断

if __name__ == '__main__':

    while True:
        INPUT = float(input('INPUT='))
        res = '正' if INPUT >= 0 else '负'    # 一行判断的技巧
        print(res)

运行结果为:

Python高级技巧: To Be More Pythonic!_第4张图片

 

8. for-else语法代替开关变量


if __name__ == '__main__':

    # for-else 可以代替开关变量...一般用于双层循环中

    A = [[1, 2, 3, 4, 2, 66], [1, 0, 2, 32, -9, 3, 4, 1, 2], [7, 8, 9, 3, 2, 2], [2, -3, 3, 1, 1, 3, 21]]
    # 上面这个矩阵, 求出全是正数的行的编号...

    print('ok var...')
    for a in A:
        ok = True
        for x in a:
            if x <= 0:  # 一旦发现存在负数,则记录ok变量并退出本层循环
                ok = False
                break
        if ok:
            print('第', A.index(a), '行全是正数')

    print('############')
    print('for-else...')
    for a in A:
        for x in a:
            if x <= 0:
                break
        else:   # 能执行到这一句说明上面的循环完整执行了,没有break
            print('第', A.index(a), '行全是正数')

运行结果为:

Python高级技巧: To Be More Pythonic!_第5张图片

你可能感兴趣的:(Python)