Showing posts with label idiomatic python. Show all posts
Showing posts with label idiomatic python. Show all posts

Sunday, December 30, 2018

An Authoritative Python Cheat Sheet (WIP)

All plagiarized of course, credits at bottom..

Make the script both a module and an executable :

if __name__ == '__main__'

The __whatever__ is a "dunder" - double-underscore. There are some useful ones you'll pick up - like __init__ , __repr__ , __eq__ (that goes along with decorators), etc.

Enumerate :

for i, var in enumerate( list_name ) :
     some_useful_code using i and var

List comprehension (build a list on the fly ) :

[ x * 3 for x in data if x > 10 ]

Build a dict out of two lists :

d = dict( zip( key_list, val_list ) )

Flatten a list of lists :

>>> l_of_lists = [list(range(10)), list(range(20,30)), list(range(50,60))]
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]
>>> l = [y for x in l_of_lists for y in x]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]


Count number of elements in your list greater than a certain value :

sum(i > 5 for i in j)

Reverse a list :

list_name[::-1]

Parse JSON data :

import json
import requests
response = requests.get( url, params=paramDict)
parsed_json = response.json()     # then do a pprint (pretty print) to see how to use..

Pandas :

import pandas as pd
df = pd.read_csv( 'somefile.csv')
matching_list = df['field1'][df['fieldN' == 'something_specific']

import matplotlib.pyplot as plt
from matplotlib import style

style.use('classic')
df['some field'].plot()
plt.show()

To convert from JSON to dataframe :

from pandas.io.json import json_normalize
df = json_normalize( parsed_json['key name'] )

Fill out a matrix using a list or dict ( while you count from 0 to 8 generate (0,0),(0,1),(0,2),(1,0)..(2,2) )

from itertools import product

i=0
for t1, t2 in product( sorted_tags, sorted_tags ) :
    row = i // num_tags
    col = i % num_tags
    i += 1
    t_mx[row][col] = transition_counts[ (t1,t2) ]

Actually, more pythonically (maybe) :


from itertools import product

for i,j in product( range( num_tags), range(num_tags) ) :
 t_mx[i,j] = transition_counts[ (sorted_tags[i], sorted_tags[j] ) ]

QEI

http://safehammad.com/downloads/python-idioms-2014-01-16.pdf
https://coderwall.com/p/rcmaea/flatten-a-list-of-lists-in-one-line-in-python