Showing posts with label cheat sheet. Show all posts
Showing posts with label cheat sheet. Show all posts

Wednesday, February 19, 2020

Python Resources - Online Interpreters and More

Who else but GOOG would know about this?

Additional Python resources

While this course will give you information about how Python works and how to write scripts in Python, you’ll likely want to find out more about specific parts of the language. Here are some great ways to help you find additional info: 
Strings :

String operations


  • len(string) Returns the length of the string
  • for character in string Iterates over each character in the string
  • if substring in string Checks whether the substring is part of the string
  • string[i] Accesses the character at index i of the string, starting at zero
  • string[i:j] Accesses the substring starting at index i, ending at index j-1. If i is omitted, it's 0 by default. If j is omitted, it's len(string) by default.

String methods

  • string.lower() / string.upper() Returns a copy of the string with all lower / upper case characters
  • string.lstrip() / string.rstrip() / string.strip() Returns a copy of the string without left / right / left or right whitespace
  • string.count(substring) Returns the number of times substring is present in the string
  • string.isnumeric() Returns True if there are only numeric characters in the string. If not, returns False.
  • string.isalpha() Returns True if there are only alphabetic characters in the string. If not, returns False.
  • string.split() / string.split(delimiter) Returns a list of substrings that were separated by whitespace / delimiter
  • string.replace(old, new) Returns a new string where all occurrences of old have been replaced by new.
  • delimiter.join(list of strings) Returns a new string with all the strings joined by the delimiter
Check out the official documentation for all available String methods.

Formatting expressions

ExprMeaningExample
{:d}integer value'{:d}'.format(10.5) → '10'
{:.2f}floating point with that many decimals'{:.2f}'.format(0.5) → '0.50'
{:.2s}string with that many characters'{:.2s}'.format('Python') → 'Py'
{:<6s}string aligned to the left that many spaces'{:<6s}'.format('Py') → 'Py    '
{:>6s}string aligned to the right that many spaces'{:<6s}'.format('Py') → '    Py'
{:^6s}string centered in that many spaces'{:<6s}'.format('Py') → '  Py '
Check out the official documentation for all available expressions.

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