Python tricks(1)

Introduction

This note records some hand-on tricks. Feel free to read and learn something from this article.

Notes

  • Unpack serialized data(if you don’t want some specific data):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> serialized_data = ['123', 'GOOG', 123, '123']
    >>> _, share, count, _ = serialized_data
    >>> share
    'GOOG'
    >>> count
    123
    >>> first, *many_values, last = serialized_data
    >>> many_values
    ['GOOG', 123]
  • Save most recent several elements:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>> q = deque(maxlen=3)
    >>> q.append(1)
    >>> q.append(2)
    >>> q.append(3)
    >>> q
    [1, 2, 3]
    >>> q.append(4)
    >>> q
    [2, 3, 4]
  • Orderedlist used additional single linked list to store the keys.

  • zip() will create an iterator that could be traversed for only once.

    1
    2
    3
    >>> prices_and_names = zip(prices.values(), prices.keys())
    >>> print(min(prices_and_names)) # OK
    >>> print(max(oruces_and_names)) # ValueError: max() arg is an empty sequence
  • with statement calls the __enter__() function when evaluating the expression or entering the with block and it assigns the return value to the variable after as keyword. When the codes go out of the with statement, the codes will call __exit__() function even though an exception is raised.

  • Functions in Python are actually objects. Function has type and id. They can be passed as an parameter or assigned to other variable.