Planning to figure out problems of Python that confused me for a long phase.
The blog trace the steps of my study.
Handling int()
Official explain about this build-in function: https://docs.python.org/3/library/functions.html#int
Just found out that there is an arguement called base
, e.g., int('010', 2).
In the past, when I was handling the value of form from user in web application, the program was quite not robust. For example, the program will easily crash if user input twelve in the register form of age.
So exception could be used to solve this problem:
1 | try: |
Lambda, filter, reduce and map
Summary: http://www.python-course.eu/lambda.php
filter a list:
1 | In [10]: list(filter(lambda x:x>0, a)) |
In Python 2.x, filter
returned a list, but in Python 3.x, it returns an iterator.
iterator: https://docs.python.org/3/tutorial/classes.html#iterators
Or
1 | In [23]: [i for i in l if i>0] |
filter a dict:
1 | from random import randint |
random.randint(a, b):
Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).
filter a set:Python3 Set:
https://docs.python.org/3/tutorial/datastructures.html#sets
enum for tuple
1. global variable:
NAME, AGE, EMAIL = range(3)
2. namedtuple:
doc: https://docs.python.org/3/library/collections.html?highlight=namedtuple#collections.namedtuple
1 | from collections import namedtuple |
Dictionary
Sorting a dictionary by value:
1 | sorted(data.items(), key=lambda x:x[1], reverse=True) |
Finding matching keys of dictionaries
1 | from random import randint, sample |
OrderedDict
doc: https://docs.python.org/3/library/collections.html?highlight=ordereddict#collections.OrderedDict
Random-sample:
random: https://docs.python.org/3/library/random.html
random.sample:
1 | In [107]: l = 'abcdefg' |
Python list implementation
http://www.laurentluce.com/posts/python-list-implementation/