diff --git a/README.md b/README.md index 2740462..a9868a3 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Python and Libraries Cheatsheet Main ---- -``` +```python if __name__ == '__main__': main() ``` @@ -11,7 +11,7 @@ if __name__ == '__main__': List ---- -``` +```python [::] .extend() .sort() @@ -22,7 +22,7 @@ sorted_by_second = sorted(, key=lambda tup: tup[1]) Dictionary ---------- -``` +```python .items() .get(, ) .setdefault(, ) @@ -31,7 +31,7 @@ Dictionary Set --- -``` +```python = set() .add() .update() @@ -42,7 +42,7 @@ Set Range ----- -``` +```python range() range(, ) range(, , ) # Negative step for backward @@ -50,17 +50,17 @@ range(, , ) # Negative step for backwa Enumerate --------- -``` +```python for i, in enumerate() ``` Type ---- -``` +```python type() is int/str/set/list ``` -``` +```python import numbers isinstance(, numbers.Number) ``` @@ -68,7 +68,7 @@ isinstance(, numbers.Number) String ------ -``` +```python str.replace(, , ) .isnumeric() .split() @@ -77,23 +77,23 @@ str.replace(, , ) ``` ### Print -``` +```python print(, , end='', sep='', file=) ``` ### Regex -``` +```python import re re.sub(, , ) re.search(, ) ``` ### Format -``` +```python '{}'.format() ``` -``` +```python {:} -> ' ' {:>} -> ' ' {:^} -> ' ' @@ -104,7 +104,7 @@ re.search(, ) ``` ### Text Wrap -``` +```python import textwrap textwrap.wrap(, ) ``` @@ -112,7 +112,7 @@ textwrap.wrap(, ) Random ------ -``` +```python import random random.random() random.randint(, ) @@ -121,13 +121,13 @@ random.shuffle() Infinity -------- -``` +```python float("inf") ``` Datetime -------- -``` +```python import datetime now = datetime.datetime.now() now.strftime('%Y%m%d') @@ -138,13 +138,13 @@ now.strftime('%Y%m%d%H%M%S') Inline ------ ### Lambda -``` +```python lambda , : lambda: ``` ### Comprehension -``` +```python [i+1 for i in range(10)] [i for i in range(10) if i>5] [i+j for i in range(10) for j in range(10)] @@ -153,7 +153,7 @@ lambda: ``` ### Map, Filter, Reduce -``` +```python A. map(lambda x: x+1, range(10)) B. filter(lambda x: x>5, range(10)) functools.reduce(combining_function, list_of_inputs) @@ -162,7 +162,7 @@ functools.reduce(combining_function, list_of_inputs) Closure ------- -``` +```python def mult_clos(x): def wrapped(y): return x * y @@ -174,7 +174,7 @@ mul_by_3 = mult_clos(3) Decorator --------- -``` +```python @closure_name def function_that_gets_passed_to_closure(): ... @@ -183,7 +183,7 @@ def function_that_gets_passed_to_closure(): Generator --------- -``` +```python def step(start, step): while True: yield start @@ -197,7 +197,7 @@ next(stepper) Class ----- ### Class -``` +```python class : def __init__(self, ): self.a = @@ -208,14 +208,14 @@ class : ``` ### Enum -``` +```python import enum class (enum.Enum): = ``` ### Copy -``` +```python import copy copy.copy() copy.deepcopy() @@ -226,49 +226,49 @@ System ------ ### Arguments -``` +```python import sys sys.argv ``` ### Read File -``` +```python with open(, encoding='utf-8') as file: return file.readlines() ``` ### Write to File -``` +```python with open(, 'w', enconding='utf-8') as file: file.write() ``` ### Execute Command -``` +```python import os os.popen().read() ``` ### Input -``` +```python filename = input('Enter a file name: ') ``` JSON ---- -``` +```python import json ``` ### Read File -``` +```python with open(, encoding='utf-8') as file: return json.load(file) ``` ### Write to File -``` +```python with open(, 'w', enconding='utf-8') as file: file.write(json.dumps()) ``` @@ -277,13 +277,13 @@ with open(, 'w', enconding='utf-8') as file: SQLite ------ -``` +```python import sqlite3 db = sqlite3.connect() ``` ### Read -``` +```python cursor = db.execute() if cursor: cursor.() @@ -291,7 +291,7 @@ db.close() ``` ### Write -``` +```python db.execute() db.commit() ``` @@ -299,19 +299,19 @@ db.commit() Threading --------- -``` +```python import threading ``` ### Thread -``` +```python thread = threading.Thread(target=, args=(, )) thread.start() thread.join() ``` ### Lock -``` +```python lock = threading.Rlock() lock.acquire() lock.release() @@ -323,62 +323,62 @@ Itertools Every function returns an generator and can accept any collection. All examples should be passed to list() to get the output. -``` +```python from itertools import * ``` ### Chain -``` +```python >>> chain([1,2], range(3,5)) [1, 2, 3, 4] ``` ### Combinations -``` +```python >>> combinations("abc", 2) [('a', 'b'), ('a', 'c'), ('b', 'c')] ``` ### Permutations -``` +```python >>> permutations("abc", 2) [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] ``` ### Compress -``` +```python >>> compress("abc", [True, 0, 23]) ['a', 'c'] ``` ### Count -``` +```python >>> a = count(5, 2) >>> next(a), next(a) (5, 7) ``` ### Cycle -``` +```python >>> a = cycle("abc") >>> [next(a) for _ in range(10)] ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a'] ``` ### Groupby -``` +```python >>> {k: list(v) for k, v in groupby("aabbbc")} {'a': ['a', 'a'], 'b': ['b', 'b', 'b'], 'c': ['c']} ``` -``` +```python >>> a = [{"id": 1, "name": "bob"}, {"id": 2, "name": "bob"}, {"id": 3, "name": "peter"}] >>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])} {'bob': [{'id': 1, 'name': 'bob'}, {'id': 2, 'name': 'bob'}], 'peter': [{'id': 3, 'name': 'peter'}]} ``` ### Product -``` +```python >>> list(product('ab', [1,2])) [('a', 1), ('a', 2), ('b', 1), ('b', 2)] ``` @@ -391,7 +391,7 @@ Introspection and Metaprograming -------------------------------- Inspecting code at runetime and code that generates code. -``` +```python >>> class B: ... def __init__(self): ... self.a= 'sdfsd' @@ -400,19 +400,19 @@ Inspecting code at runetime and code that generates code. ``` ### Getattr -``` +```python >>> getattr(b, 'a') 'sdfsd' ``` ### Hasattr -``` +```python >>> hasattr(b, 'c') False ``` ### Setattr -``` +```python >>> setattr(b, 'c', 10) ``` @@ -420,11 +420,11 @@ Type ---- Type is the root class. If only passed the object it returns it's type. Otherwise it creates new class (and not the instance!). -``` +```python type(class_name, parents[tuple], attributes[dict]) ``` -``` +```python BB = type('B', (), {'a': 'sdfsd', 'b': 123324} b = BB() ``` @@ -432,13 +432,13 @@ b = BB() MetaClass --------- Classes that creates classes. -``` +```python def my_meta_class(name, parents, attrs): ... do stuff return type(name, parents, attrs) ``` or -``` +```python class MyMetaClass(type): def __new__(klass, name, parents, attrs): ... do stuff @@ -456,7 +456,7 @@ Do Stuff Metaclass Attr -------------- When class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined, and eventually comes to type. -``` +```python class BlaBla: __metaclass__ = Bla ```