Friday, June 9, 2017

python practice

check if dict has key

if key in dict

python 3.6 install package

after 3.4, pip is not standalone, to install a package, run
python -m pip install SomePackage


returns a function with partially providing the parameters 

python threads pool

csvFiles = list(filter(isFile, os.listdir("d:/quotes")))
with  multiprocessing.Pool(multiprocessing.cpu_count() - 1) as p:, csvFiles)
Here loadCsv is the function, csvFiles is the list to iterate


with open('filename', 'a') as f:
        pickle.dump(data, f)

with open('filename', 'rb') as f:
    x = pickle.load(f)

python prirnt current exception

import traceback

zip two arrays into tuples

let's say you have two arrays [-1, 0, 1, 2] and [7,8,9,10]
you want to merge them into tuples like this [(-1, 7), (0, 8), (1, 9), (2, 10)]
list(zip(array1, array2))

array filter

result = [a for a in A if a not in subset_of_A]

python function argument

define function inside function

def method_a(arg):

    def method_b(arg):
        return some_data

    some_data = method_b

python class and inheritance

Generator and yield


Intersection - to find the same items
Difference - to find the different items
create sets using the new notation
a_set = {'red', 'blue', 'green'}
# Output: type 'set'
>>> a = {1,1,2,3}
>>> a
{1, 2, 3}


Decorator is to add a wrap to the target function. It is like the interceptor in spring framework.
When use pymongo to query mongodb, it can return Cursor or list if it is sorted. This inconsistency is quite annoying to the client code .
I added the decorator "wrapReturnToList" to make all return to be List.
def wrapReturnToList(f):
    def decorated(*args, **kwargs):
        return list(f(*args, **kwargs))
    return decorated

def getAllActiveSymbols():
    return stockDb.symbol.find({ "Status": { "$ne": SYMBOL_INACTIVE } })
Without the annotation, it returns Cursor. With the annotation, it returns List.


    zf = zipfile.ZipFile(dir + zipFileName, mode='a')
        zf.write(toZipFileFullPat, os.path.basename(toZipFileFullPath))

os.path.basename(toZipFileFullPat) is to get the file name from the full path, so that it won't zip the dir into the zip file.


defaultdict does not need to check whether a key is present or not.
from collections import defaultdict

colours = (
    ('Yasoob', 'Yellow'),
    ('Ali', 'Blue'),
    ('Arham', 'Green'),
    ('Ali', 'Black'),
    ('Yasoob', 'Red'),
    ('Ahmed', 'Silver'),

favourite_colours = defaultdict(list)

for name, colour in colours:
    favourite_colours[name].append(colour) #favourite_colours[name] may not exist, dict throws error


# output
# defaultdict(,
#    {'Arham': ['Green'],
#     'Yasoob': ['Yellow', 'Red'],
#     'Ahmed': ['Silver'],
#     'Ali': ['Blue', 'Black']
# })


Double end queue, can pop or extend items from either end.

No comments:

Post a Comment