@@ -41,16 +41,15 @@ elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
41
41
sorted_by_second = sorted (< collection> , key = lambda el : el[1 ])
42
42
sorted_by_both = sorted (< collection> , key = lambda el : (el[1 ], el[0 ]))
43
43
flattened_list = list (itertools.chain.from_iterable(< list > ))
44
- list_of_chars = list (< str > )
45
44
product_of_elems = functools.reduce(lambda out , x : out * x, < collection> )
46
- no_duplicates = list (dict .fromkeys( < list > ) )
45
+ list_of_chars = list (< str > )
47
46
```
48
47
49
48
``` python
50
49
index = < list > .index(< el> ) # Returns first index of item.
51
50
< list > .insert(index, < el> ) # Inserts item at index and moves the rest to the right.
52
51
< el> = < list > .pop([index]) # Removes and returns item at index or from the end.
53
- < list > .remove(< el> ) # Removes first occurrence of item.
52
+ < list > .remove(< el> ) # Removes first occurrence of item or raises ValueError .
54
53
< list > .clear() # Removes all items.
55
54
```
56
55
@@ -64,17 +63,17 @@ Dictionary
64
63
```
65
64
66
65
``` python
67
- value = < dict > .get(key, default) # Returns default if key does not exist.
68
- value = < dict > .setdefault(key, default) # Same, but also adds default to dict.
69
- < dict > = collections.defaultdict(< type > ) # Creates a dictionary with default value of type.
70
- < dict > = collections.defaultdict(lambda : 1 ) # Creates a dictionary with default value 1.
66
+ value = < dict > .get(key, default = None ) # Returns default if key does not exist.
67
+ value = < dict > .setdefault(key, default = None ) # Same, but also adds default to dict.
68
+ < dict > = collections.defaultdict(< type > ) # Creates a dictionary with default value of type.
69
+ < dict > = collections.defaultdict(lambda : 1 ) # Creates a dictionary with default value 1.
71
70
```
72
71
73
72
``` python
74
- < dict > .update(< dict > ) # Or: dict_a = {**dict_a, **dict_b}.
75
- < dict > = dict (< list > ) # Initiates a dict from list of key-value pairs.
76
- < dict > = dict (zip (keys, values)) # Initiates a dict from two lists.
77
- < dict > = dict .fromkeys(keys [, value]) # Initiates a dict from list of keys.
73
+ < dict > .update(< dict > ) # Or: dict_a = {**dict_a, **dict_b}.
74
+ < dict > = dict (< list > ) # Initiates a dict from list of key-value pairs.
75
+ < dict > = dict (zip (keys, values)) # Initiates a dict from two lists.
76
+ < dict > = dict .fromkeys(keys [, value]) # Initiates a dict from list of keys.
78
77
```
79
78
80
79
``` python
@@ -88,8 +87,8 @@ value = <dict>.pop(key) # Removes item from dictionary.
88
87
>> > colors = [' blue' , ' red' , ' blue' , ' yellow' , ' blue' , ' red' ]
89
88
>> > counter = Counter(colors)
90
89
Counter({' blue' : 3 , ' red' : 2 , ' yellow' : 1 })
91
- >> > counter.most_common()[0 ][ 0 ]
92
- ' blue'
90
+ >> > counter.most_common()[0 ]
91
+ ( ' blue' , 3 )
93
92
```
94
93
95
94
121
120
```
122
121
123
122
### Frozenset
124
- #### Is hashable and can be used as a key in dictionary.
123
+ #### Is hashable so it can be used as a key in dictionary.
125
124
``` python
126
125
< frozenset > = frozenset (< collection> )
127
126
```
@@ -130,10 +129,10 @@ Set
130
129
Range
131
130
-----
132
131
``` python
133
- range (to_exclusive)
134
- range (from_inclusive, to_exclusive)
135
- range (from_inclusive, to_exclusive, step_size)
136
- range (from_inclusive, to_exclusive, - step_size)
132
+ < range > = range (to_exclusive)
133
+ < range > = range (from_inclusive, to_exclusive)
134
+ < range > = range (from_inclusive, to_exclusive, step_size)
135
+ < range > = range (from_inclusive, to_exclusive, - step_size)
137
136
```
138
137
139
138
``` python
@@ -153,7 +152,8 @@ for i, el in enumerate(<collection> [, i_start]):
153
152
Named Tuple
154
153
-----------
155
154
``` python
156
- >> > Point = collections.namedtuple(' Point' , ' x y' )
155
+ >> > from collections import namedtuple
156
+ >> > Point = namedtuple(' Point' , ' x y' )
157
157
>> > p = Point(1 , y = 2 )
158
158
Point(x = 1 , y = 2 )
159
159
>> > p[0 ]
@@ -188,7 +188,7 @@ for line in iter(partial(input, 'Please enter value: '), ''):
188
188
```
189
189
190
190
### Next
191
- ** Returns next item. If there are no more items it raises exception or returns default if specified.**
191
+ ** Returns next item. If there are no more items it raises StopIteration exception or returns default if specified.**
192
192
``` python
193
193
< el> = next (< iter > [, default])
194
194
```
@@ -252,7 +252,7 @@ String
252
252
< str > = < str > .replace(old_str, new_str)
253
253
< bool > = < str > .startswith(< sub_str> ) # Pass tuple of strings for multiple options.
254
254
< bool > = < str > .endswith(< sub_str> ) # Pass tuple of strings for multiple options.
255
- < int > = < str > .index(< sub_str> ) # Returns first index of a substring .
255
+ < int > = < str > .index(< sub_str> ) # Returns start index of first match .
256
256
< bool > = < str > .isnumeric() # True if str contains only numeric characters.
257
257
< list > = textwrap.wrap(< str > , width) # Nicely breaks string into lines.
258
258
```
@@ -288,7 +288,7 @@ import re
288
288
* ** Parameter ` 'flags=re.IGNORECASE' ` can be used with all functions.**
289
289
* ** Parameter ` 'flags=re.DOTALL' ` makes dot also accept newline.**
290
290
* ** Use ` r'\1' ` or ` '\\\\1' ` for backreference.**
291
- * ** Use ` '?' ` to make operators non-greedy.**
291
+ * ** Use ` '?' ` to make operator non-greedy.**
292
292
293
293
### Match Object
294
294
``` python
@@ -300,7 +300,7 @@ import re
300
300
```
301
301
302
302
### Special Sequences
303
- ** Use capital letter for negation.**
303
+ ** Expressions below hold true only for strings that contain only ASCII characters. Use capital letter for negation.**
304
304
``` python
305
305
' \d' == ' [0-9]' # Digit
306
306
' \s' == ' [ \t\n\r\f\v ]' # Whitespace
@@ -318,10 +318,10 @@ Format
318
318
``` python
319
319
>> > Person = namedtuple(' Person' , ' name height' )
320
320
>> > person = Person(' Jean-Luc' , 187 )
321
- >> > f ' { person.height:10 } '
322
- ' 187'
323
- >> > ' {p.height:10 } ' .format(p = person)
324
- ' 187'
321
+ >> > f ' { person.height} '
322
+ ' 187'
323
+ >> > ' {p.height} ' .format(p = person)
324
+ ' 187'
325
325
```
326
326
327
327
### General Options
@@ -581,7 +581,7 @@ from functools import partial
581
581
```
582
582
583
583
### Nonlocal
584
- ** 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.**
584
+ ** 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' .**
585
585
586
586
``` python
587
587
def get_counter ():
@@ -668,7 +668,7 @@ class <name>:
668
668
def __init__ (self , a ):
669
669
self .a = a
670
670
def __repr__ (self ):
671
- class_name = type ( self ) .__name__
671
+ class_name = self . __class__ .__name__
672
672
return f ' { class_name} ( { self .a!r } ) '
673
673
def __str__ (self ):
674
674
return str (self .a)
@@ -870,13 +870,6 @@ KeyboardInterrupt
870
870
871
871
System
872
872
------
873
- ### Command Line Arguments
874
- ``` python
875
- import sys
876
- script_name = sys.argv[0 ]
877
- arguments = sys.argv[1 :]
878
- ```
879
-
880
873
### Print Function
881
874
``` python
882
875
print (< el_1> , ... , sep = ' ' , end = ' \n ' , file = sys.stdout, flush = False )
@@ -974,7 +967,9 @@ b'.\n..\nfile1.txt\nfile2.txt\n'
974
967
>> > sys.setrecursionlimit(5000 )
975
968
```
976
969
977
- ### Path
970
+
971
+ Path
972
+ ----
978
973
``` python
979
974
from os import path, listdir
980
975
< bool > = path.exists(' <path>' )
@@ -989,9 +984,7 @@ from os import path, listdir
989
984
[' 1.gif' , ' card.gif' ]
990
985
```
991
986
992
-
993
- Pathlib
994
- -------
987
+ ### Pathlib
995
988
** This module offers classes representing filesystem paths with semantics appropriate for different operating systems.**
996
989
997
990
``` python
@@ -1023,6 +1016,36 @@ pwd = Path()
1023
1016
```
1024
1017
1025
1018
1019
+ Command Line Arguments
1020
+ ----------------------
1021
+ ``` python
1022
+ import sys
1023
+ script_name = sys.argv[0 ]
1024
+ arguments = sys.argv[1 :]
1025
+ ```
1026
+
1027
+ ### Argparse
1028
+ ``` python
1029
+ from argparse import ArgumentParser
1030
+ desc = ' calculate X to the power of Y'
1031
+ parser = ArgumentParser(description = desc)
1032
+ group = parser.add_mutually_exclusive_group()
1033
+ group.add_argument(' -v' , ' --verbose' , action = ' store_true' )
1034
+ group.add_argument(' -q' , ' --quiet' , action = ' store_true' )
1035
+ parser.add_argument(' x' , type = int , help = ' the base' )
1036
+ parser.add_argument(' y' , type = int , help = ' the exponent' )
1037
+ args = parser.parse_args()
1038
+ answer = args.x ** args.y
1039
+
1040
+ if args.quiet:
1041
+ print (answer)
1042
+ elif args.verbose:
1043
+ print (f ' { args.x} to the power { args.y} equals { answer} ' )
1044
+ else :
1045
+ print (f ' { args.x} ^ { args.y} == { answer} ' )
1046
+ ```
1047
+
1048
+
1026
1049
JSON
1027
1050
----
1028
1051
``` python
@@ -1037,14 +1060,14 @@ from collections import OrderedDict
1037
1060
< object > = json.loads(< str > , object_pairs_hook = OrderedDict)
1038
1061
```
1039
1062
1040
- ### Read File
1063
+ ### Read Object from JSON File
1041
1064
``` python
1042
1065
def read_json_file (filename ):
1043
1066
with open (filename, encoding = ' utf-8' ) as file :
1044
1067
return json.load(file )
1045
1068
```
1046
1069
1047
- ### Write to File
1070
+ ### Write Object to JSON File
1048
1071
``` python
1049
1072
def write_to_json_file (filename , an_object ):
1050
1073
with open (filename, ' w' , encoding = ' utf-8' ) as file :
@@ -1079,7 +1102,7 @@ SQLite
1079
1102
------
1080
1103
``` python
1081
1104
import sqlite3
1082
- db = sqlite3.connect(< filename > )
1105
+ db = sqlite3.connect(' <path> ' )
1083
1106
...
1084
1107
db.close()
1085
1108
```
@@ -1114,7 +1137,7 @@ Bytes
1114
1137
``` python
1115
1138
< bytes > = < str > .encode(encoding = ' utf-8' )
1116
1139
< bytes > = < int > .to_bytes(length, byteorder = ' big|little' , signed = False )
1117
- < bytes > = bytes .fromhex(< hex > )
1140
+ < bytes > = bytes .fromhex(' <hex>' )
1118
1141
```
1119
1142
1120
1143
### Decode
@@ -1166,7 +1189,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03'
1166
1189
* ** ` '<' ` - little-endian**
1167
1190
* ** ` '>' ` - big-endian**
1168
1191
1169
- #### Use capital letter for unsigned type. Standard size in brackets:
1192
+ #### Use capital letter for unsigned type. Standard sizes are in brackets:
1170
1193
* ** ` 'x' ` - pad byte**
1171
1194
* ** ` 'c' ` - char (1)**
1172
1195
* ** ` 'h' ` - short (2)**
@@ -1183,7 +1206,7 @@ Array
1183
1206
1184
1207
``` python
1185
1208
from array import array
1186
- < array> = array(< typecode> [, < collection> ])
1209
+ < array> = array(' <typecode>' [, < collection> ])
1187
1210
```
1188
1211
1189
1212
@@ -1208,8 +1231,8 @@ from collections import deque
1208
1231
1209
1232
``` python
1210
1233
< deque> .appendleft(< el> )
1211
- < deque> .extendleft(< collection> ) # Collection gets reversed.
1212
1234
< el> = < deque> .popleft()
1235
+ < deque> .extendleft(< collection> ) # Collection gets reversed.
1213
1236
< deque> .rotate(n = 1 ) # Rotates elements to the right.
1214
1237
```
1215
1238
@@ -1304,7 +1327,10 @@ from itertools import *
1304
1327
>> > # islice(<collection>, from_inclusive, to_exclusive)
1305
1328
>> > islice([1 , 2 , 3 ], 1 , None )
1306
1329
[2 , 3 ]
1330
+ ```
1307
1331
1332
+ ### Group by
1333
+ ``` python
1308
1334
>> > people = [{' id' : 1 , ' name' : ' Bob' },
1309
1335
{' id' : 2 , ' name' : ' Bob' },
1310
1336
{' id' : 3 , ' name' : ' Peter' }]
@@ -1367,7 +1393,7 @@ param_names = list(sig.parameters.keys())
1367
1393
** 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!).**
1368
1394
1369
1395
``` python
1370
- type (< class_name> , < parents_tuple> , < attributes_dict> )
1396
+ < class > = type (< class_name> , < parents_tuple> , < attributes_dict> )
1371
1397
```
1372
1398
1373
1399
``` python
@@ -1482,7 +1508,7 @@ def eval_node(node):
1482
1508
1483
1509
Coroutine
1484
1510
---------
1485
- * ** Similar to Generator , but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
1511
+ * ** Similar to generator , but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().**
1486
1512
* ** Coroutines provide more powerful data routing possibilities than iterators.**
1487
1513
* ** If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
1488
1514
@@ -1551,29 +1577,6 @@ pyplot.show()
1551
1577
```
1552
1578
1553
1579
1554
- Argparse
1555
- --------
1556
- ``` python
1557
- from argparse import ArgumentParser
1558
- desc = ' calculate X to the power of Y'
1559
- parser = ArgumentParser(description = desc)
1560
- group = parser.add_mutually_exclusive_group()
1561
- group.add_argument(' -v' , ' --verbose' , action = ' store_true' )
1562
- group.add_argument(' -q' , ' --quiet' , action = ' store_true' )
1563
- parser.add_argument(' x' , type = int , help = ' the base' )
1564
- parser.add_argument(' y' , type = int , help = ' the exponent' )
1565
- args = parser.parse_args()
1566
- answer = args.x ** args.y
1567
-
1568
- if args.quiet:
1569
- print (answer)
1570
- elif args.verbose:
1571
- print (f ' { args.x} to the power { args.y} equals { answer} ' )
1572
- else :
1573
- print (f ' { args.x} ^ { args.y} == { answer} ' )
1574
- ```
1575
-
1576
-
1577
1580
Table
1578
1581
-----
1579
1582
#### Prints CSV file as ASCII table:
@@ -1641,12 +1644,14 @@ Audio
1641
1644
#### Saves a list of floats with values between -1 and 1 to a WAV file:
1642
1645
``` python
1643
1646
import wave, struct
1644
- samples = [struct.pack(' <h' , int (a * 30000 )) for a in < list > ]
1647
+ samples_f = [struct.pack(' <h' , int (a * 30000 )) for a in < list > ]
1648
+ samples_b = b ' ' .join(samples_f)
1649
+
1645
1650
wf = wave.open(' test.wav' , ' wb' )
1646
1651
wf.setnchannels(1 )
1647
1652
wf.setsampwidth(2 )
1648
1653
wf.setframerate(44100 )
1649
- wf.writeframes(b ' ' .join(samples) )
1654
+ wf.writeframes(samples_b )
1650
1655
wf.close()
1651
1656
```
1652
1657
0 commit comments