From 68dd21b78b80ac9d67a1b2d3d1ab0d640bbe4e6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 22 Feb 2019 19:24:55 +0100 Subject: [PATCH] A lot of small changes --- README.md | 153 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 79 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index 5f458ef..580398a 100644 --- a/README.md +++ b/README.md @@ -41,16 +41,15 @@ elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)] sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) flattened_list = list(itertools.chain.from_iterable()) -list_of_chars = list() product_of_elems = functools.reduce(lambda out, x: out * x, ) -no_duplicates = list(dict.fromkeys()) +list_of_chars = list() ``` ```python index = .index() # Returns first index of item. .insert(index, ) # Inserts item at index and moves the rest to the right. = .pop([index]) # Removes and returns item at index or from the end. -.remove() # Removes first occurrence of item. +.remove() # Removes first occurrence of item or raises ValueError. .clear() # Removes all items. ``` @@ -64,17 +63,17 @@ Dictionary ``` ```python -value = .get(key, default) # Returns default if key does not exist. -value = .setdefault(key, default) # Same, but also adds default to dict. - = collections.defaultdict() # Creates a dictionary with default value of type. - = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. +value = .get(key, default=None) # Returns default if key does not exist. +value = .setdefault(key, default=None) # Same, but also adds default to dict. + = collections.defaultdict() # Creates a dictionary with default value of type. + = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. ``` ```python -.update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Initiates a dict from list of key-value pairs. - = dict(zip(keys, values)) # Initiates a dict from two lists. - = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys. +.update() # Or: dict_a = {**dict_a, **dict_b}. + = dict() # Initiates a dict from list of key-value pairs. + = dict(zip(keys, values)) # Initiates a dict from two lists. + = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys. ``` ```python @@ -88,8 +87,8 @@ value = .pop(key) # Removes item from dictionary. >>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] >>> counter = Counter(colors) Counter({'blue': 3, 'red': 2, 'yellow': 1}) ->>> counter.most_common()[0][0] -'blue' +>>> counter.most_common()[0] +('blue', 3) ``` @@ -121,7 +120,7 @@ Set ``` ### Frozenset -#### Is hashable and can be used as a key in dictionary. +#### Is hashable so it can be used as a key in dictionary. ```python = frozenset() ``` @@ -130,10 +129,10 @@ Set Range ----- ```python -range(to_exclusive) -range(from_inclusive, to_exclusive) -range(from_inclusive, to_exclusive, step_size) -range(from_inclusive, to_exclusive, -step_size) + = range(to_exclusive) + = range(from_inclusive, to_exclusive) + = range(from_inclusive, to_exclusive, step_size) + = range(from_inclusive, to_exclusive, -step_size) ``` ```python @@ -153,7 +152,8 @@ for i, el in enumerate( [, i_start]): Named Tuple ----------- ```python ->>> Point = collections.namedtuple('Point', 'x y') +>>> from collections import namedtuple +>>> Point = namedtuple('Point', 'x y') >>> p = Point(1, y=2) Point(x=1, y=2) >>> p[0] @@ -188,7 +188,7 @@ for line in iter(partial(input, 'Please enter value: '), ''): ``` ### Next -**Returns next item. If there are no more items it raises exception or returns default if specified.** +**Returns next item. If there are no more items it raises StopIteration exception or returns default if specified.** ```python = next( [, default]) ``` @@ -252,7 +252,7 @@ String = .replace(old_str, new_str) = .startswith() # Pass tuple of strings for multiple options. = .endswith() # Pass tuple of strings for multiple options. - = .index() # Returns first index of a substring. + = .index() # Returns start index of first match. = .isnumeric() # True if str contains only numeric characters. = textwrap.wrap(, width) # Nicely breaks string into lines. ``` @@ -288,7 +288,7 @@ import re * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** * **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** * **Use `r'\1'` or `'\\\\1'` for backreference.** -* **Use `'?'` to make operators non-greedy.** +* **Use `'?'` to make operator non-greedy.** ### Match Object ```python @@ -300,7 +300,7 @@ import re ``` ### Special Sequences -**Use capital letter for negation.** +**Expressions below hold true only for strings that contain only ASCII characters. Use capital letter for negation.** ```python '\d' == '[0-9]' # Digit '\s' == '[ \t\n\r\f\v]' # Whitespace @@ -318,10 +318,10 @@ Format ```python >>> Person = namedtuple('Person', 'name height') >>> person = Person('Jean-Luc', 187) ->>> f'{person.height:10}' -' 187' ->>> '{p.height:10}'.format(p=person) -' 187' +>>> f'{person.height}' +'187' +>>> '{p.height}'.format(p=person) +'187' ``` ### General Options @@ -581,7 +581,7 @@ from functools import partial ``` ### Nonlocal -**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as global or nonlocal.** +**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as 'global' or 'nonlocal'.** ```python def get_counter(): @@ -668,7 +668,7 @@ class : def __init__(self, a): self.a = a def __repr__(self): - class_name = type(self).__name__ + class_name = self.__class__.__name__ return f'{class_name}({self.a!r})' def __str__(self): return str(self.a) @@ -870,13 +870,6 @@ KeyboardInterrupt System ------ -### Command Line Arguments -```python -import sys -script_name = sys.argv[0] -arguments = sys.argv[1:] -``` - ### Print Function ```python print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) @@ -974,7 +967,9 @@ b'.\n..\nfile1.txt\nfile2.txt\n' >>> sys.setrecursionlimit(5000) ``` -### Path + +Path +---- ```python from os import path, listdir = path.exists('') @@ -989,9 +984,7 @@ from os import path, listdir ['1.gif', 'card.gif'] ``` - -Pathlib -------- +### Pathlib **This module offers classes representing filesystem paths with semantics appropriate for different operating systems.** ```python @@ -1023,6 +1016,36 @@ pwd = Path() ``` +Command Line Arguments +---------------------- +```python +import sys +script_name = sys.argv[0] +arguments = sys.argv[1:] +``` + +### Argparse +```python +from argparse import ArgumentParser +desc = 'calculate X to the power of Y' +parser = ArgumentParser(description=desc) +group = parser.add_mutually_exclusive_group() +group.add_argument('-v', '--verbose', action='store_true') +group.add_argument('-q', '--quiet', action='store_true') +parser.add_argument('x', type=int, help='the base') +parser.add_argument('y', type=int, help='the exponent') +args = parser.parse_args() +answer = args.x ** args.y + +if args.quiet: + print(answer) +elif args.verbose: + print(f'{args.x} to the power {args.y} equals {answer}') +else: + print(f'{args.x}^{args.y} == {answer}') +``` + + JSON ---- ```python @@ -1037,14 +1060,14 @@ from collections import OrderedDict = json.loads(, object_pairs_hook=OrderedDict) ``` -### Read File +### Read Object from JSON File ```python def read_json_file(filename): with open(filename, encoding='utf-8') as file: return json.load(file) ``` -### Write to File +### Write Object to JSON File ```python def write_to_json_file(filename, an_object): with open(filename, 'w', encoding='utf-8') as file: @@ -1079,7 +1102,7 @@ SQLite ------ ```python import sqlite3 -db = sqlite3.connect() +db = sqlite3.connect('') ... db.close() ``` @@ -1114,7 +1137,7 @@ Bytes ```python = .encode(encoding='utf-8') = .to_bytes(length, byteorder='big|little', signed=False) - = bytes.fromhex() + = bytes.fromhex('') ``` ### Decode @@ -1166,7 +1189,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' * **`'<'` - little-endian** * **`'>'` - big-endian** -#### Use capital letter for unsigned type. Standard size in brackets: +#### Use capital letter for unsigned type. Standard sizes are in brackets: * **`'x'` - pad byte** * **`'c'` - char (1)** * **`'h'` - short (2)** @@ -1183,7 +1206,7 @@ Array ```python from array import array - = array( [, ]) + = array('' [, ]) ``` @@ -1208,8 +1231,8 @@ from collections import deque ```python .appendleft() -.extendleft() # Collection gets reversed. = .popleft() +.extendleft() # Collection gets reversed. .rotate(n=1) # Rotates elements to the right. ``` @@ -1304,7 +1327,10 @@ from itertools import * >>> # islice(, from_inclusive, to_exclusive) >>> islice([1, 2, 3], 1, None) [2, 3] +``` +### Group by +```python >>> people = [{'id': 1, 'name': 'Bob'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Peter'}] @@ -1367,7 +1393,7 @@ param_names = list(sig.parameters.keys()) **Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!).** ```python -type(, , ) + = type(, , ) ``` ```python @@ -1482,7 +1508,7 @@ def eval_node(node): Coroutine --------- -* **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().** +* **Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().** * **Coroutines provide more powerful data routing possibilities than iterators.** * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.** @@ -1551,29 +1577,6 @@ pyplot.show() ``` -Argparse --------- -```python -from argparse import ArgumentParser -desc = 'calculate X to the power of Y' -parser = ArgumentParser(description=desc) -group = parser.add_mutually_exclusive_group() -group.add_argument('-v', '--verbose', action='store_true') -group.add_argument('-q', '--quiet', action='store_true') -parser.add_argument('x', type=int, help='the base') -parser.add_argument('y', type=int, help='the exponent') -args = parser.parse_args() -answer = args.x ** args.y - -if args.quiet: - print(answer) -elif args.verbose: - print(f'{args.x} to the power {args.y} equals {answer}') -else: - print(f'{args.x}^{args.y} == {answer}') -``` - - Table ----- #### Prints CSV file as ASCII table: @@ -1641,12 +1644,14 @@ Audio #### Saves a list of floats with values between -1 and 1 to a WAV file: ```python import wave, struct -samples = [struct.pack('] +samples_f = [struct.pack('] +samples_b = b''.join(samples_f) + wf = wave.open('test.wav', 'wb') wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(44100) -wf.writeframes(b''.join(samples)) +wf.writeframes(samples_b) wf.close() ```