Python 奇技淫巧

  • 数组降维

    1
    2
    3
    matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    [k for i in matrix for k in i]
    >>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 矩阵行列互转

    1
    2
    3
    a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    re_a = list(zip(*a))
    >>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
  • 字典的键、值互换

    1
    2
    3
    4
    5
    6
    a = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    def reverse_dict(a):
    k = a.keys()
    v = a.values()
    new_dict = dict(zip(v, k))
    return new_dict
  • 合并一个list的相邻项

    1
    2
    3
    a = [1, 2, 3, 4, 5, 6]
    list(zip( a[::2], a[1::2] ))
    >>> [(1, 2), (3, 4), (5, 6)]
  • 反转字符串

    1
    2
    3
    a = 'python'
    a[::-1]
    >>> 'nohtyp'
  • 统计list中1的个数

1
2
3
a = [0, 1, 0, 0, 1, 0, 1, 0]
[i[0] for i in enumerate(a) if i[1] != 0]
>>>[1, 4, 6]