File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ # Explaining partial function and how to use it
2+ # Importing partial from functools
3+ from functools import partial
4+
5+ # Assigning to x integer number in binary notation
6+ x = int ('1101' , base = 2 )
7+ print (x ) # Showing result in decimal notation
8+
9+ # Creating function int_2 with partial
10+ int_2 = partial (int , base = 2 )
11+ x = int_2 ('1101' )
12+ print (x )
13+
14+
15+ # Another examples how to sort lists easier with partial
16+ x = [
17+ ('Guido' , 'van' , 'Rossum' ),
18+ ('Haskell' , 'Curry' ),
19+ ('John' , 'Backus' )
20+ ]
21+
22+ y = ['abc' , 'cba' , 'abb' ]
23+
24+ import operator as op
25+
26+ # Creating function to sort lists by last element
27+ sort_by_last = partial (list .sort , key = op .itemgetter (- 1 ))
28+
29+ print (x ) # Showing current list
30+ sort_by_last (x )
31+ print (x ) # Showing sorted list
32+
33+ sort_by_last (y )
34+ print (y )
You can’t perform that action at this time.
0 commit comments