当前位置 主页 > 网站技术 > 代码类 >

    40个你可能不知道的Python技巧附代码

    栏目:代码类 时间:2020-01-30 06:11

    1、拆箱

    >>> a, b, c = 1, 2, 3
    >>> a, b, c
    (1, 2, 3)
    >>> a, b, c = [1, 2, 3]
    >>> a, b, c
    (1, 2, 3)
    >>> a, b, c = (2 * i + 1 for i in range(3))
    >>> a, b, c
    (1, 3, 5)
    >>> a, (b, c), d = [1, (2, 3), 4]
    >>> a
    1
    >>> b
    2
    >>> c
    3
    >>> d
    4

    2、使用拆箱进行变量交换

    >>> a, b = 1, 2
    >>> a, b = b, a
    >>> a, b
    (2, 1)

    3、扩展的拆箱(Python 3支持)

    >>> a, *b, c = [1, 2, 3, 4, 5]
    >>> a
    1
    >>> b
    [2, 3, 4]
    >>> c
    5

    4、负数索引

    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> a[-1]
    10
    >>> a[-3]
    8

    5、列表切片(a[start:end])

    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> a[2:8]
    [2, 3, 4, 5, 6, 7]

    6、负数索引的列表切片

    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> a[-4:-2]
    [7, 8]

    7、带步数的列表切片(a[start:end:step])

    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> a[::2]
    [0, 2, 4, 6, 8, 10]
    >>> a[::3]
    [0, 3, 6, 9]
    >>> a[2:8:2]
    [2, 4, 6]
    

    8、负数步数的列表切片

    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> a[::-1]
    [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    >>> a[::-2]
    [10, 8, 6, 4, 2, 0]

    9、列表切片赋值

    >>> a = [1, 2, 3, 4, 5]
    >>> a[2:3] = [0, 0]
    >>> a
    [1, 2, 0, 0, 4, 5]
    >>> a[1:1] = [8, 9]
    >>> a
    [1, 8, 9, 2, 0, 0, 4, 5]
    >>> a[1:-1] = []
    >>> a
    [1, 5]

    10、切片命名(slice(start, end, step))

    >>> a = [0, 1, 2, 3, 4, 5]
    >>> LASTTHREE = slice(-3, None)
    >>> LASTTHREE
    slice(-3, None, None)
    >>> a[LASTTHREE]
    [3, 4, 5]

    11、遍历列表索引和值(enumerate)

    >>> a = ["Hello", "world", "!"]
    >>> for i, x in enumerate(a):
    ... print "{}: {}".format(i, x)
    ...
    0: Hello
    1: world
    2: !

    12、遍历字典的KEY和VALUE(dict.iteritems)

    >>> m = {"a": 1, "b": 2, "c": 3, "d": 4}
    >>> for k, v in m.iteritems():
    ... print "{}: {}".format(k, v)
    ...
    a: 1
    c: 3
    b: 2
    d: 4
     
    # 注意:Python 3中要使用dict.items

    13、压缩 & 解压列表和可遍历对象

    >>> a = [1, 2, 3]
    >>> b = ["a", "b", "c"]
    >>> z = zip(a, b)
    >>> z
    [(1, "a"), (2, "b"), (3, "c")]
    >>> zip(*z)
    [(1, 2, 3), ("a", "b", "c")]

    14、使用zip分组相邻列表项

    >>> a = [1, 2, 3, 4, 5, 6]
     
    >>> # Using iterators
    >>> group_adjacent = lambda a, k: zip(*([iter(a)] * k))
    >>> group_adjacent(a, 3)
    [(1, 2, 3), (4, 5, 6)]
    >>> group_adjacent(a, 2)
    [(1, 2), (3, 4), (5, 6)]
    >>> group_adjacent(a, 1)
    [(1,), (2,), (3,), (4,), (5,), (6,)]
     
     
    >>> # Using slices
    >>> from itertools import islice
    >>> group_adjacent = lambda a, k: zip(*(islice(a, i, None, k) for i in range(k)))
    >>> group_adjacent(a, 3)
    [(1, 2, 3), (4, 5, 6)]
    >>> group_adjacent(a, 2)
    [(1, 2), (3, 4), (5, 6)]
    >>> group_adjacent(a, 1)
    [(1,), (2,), (3,), (4,), (5,), (6,)]