Python Notes

Basic

package import

If the import module in the same dir

1
from . import core

If the import module in the top dir

1
from .. import core

If the import module in the other subdir

1
from ..other import core

List

generate fixed length of empty list

1
list = [0]*26

String

reverse the string

1
2
3
st = '1101010'
st1 = st[::-1]
print st1

Tuple

named tuple

1
2
3
from collections import namedtuple
Stock = namedtuple("Stock", "symbol current high low")
stock = Stock("GOOG", 613.30, high=625.86, low=610.50)

builtin

ord(…)

Return the integer ordinal of a one-character string.

1
2
print ord('b')
>> 98

collections module

defaultdict

defaultdict means that if a key is not found in the dictionary, then instead of
a KeyError being thrown, a new entry is created. The type of the new entry is
given by the argument of defaultdict.

1
2
3
4
5
somedict = {}
print(somedict[3]) # KeyError

somedict = defaultdict(int)
print(somedict[3]) # print int(),thus 0

1
2
3
4
5
6
7
8
9
>>> ice_cream = defaultdict(lambda: 'Vanilla')
>>>
>>> ice_cream = defaultdict(lambda: 'Vanilla')
>>> ice_cream['Sarah'] = 'Chunky Monkey'
>>> ice_cream['Abdul'] = 'Butter Pecan'
>>> print ice_cream['Sarah']
Chunky Monkey
>>> print ice_cream['Joe']
Vanilla