Pythonic programming examples and Analysis
1. List
List [start: end: Increment]
Value Transfer and address transfer
A = [] B = a # address transfer B = a [:] value transfer a. sort () print a # [] print B # []
2. sort ()
D = {1:'s ', 2: 'A'} print sorted (d. items (), key = lambda x: x [1])/* sort by 2nd elements of the list element */
# Sorted (iterable, cmp = None/* function */, key = None/* function */, reverse = False) ll = ['aaa', 'A ', 'A'] ll. sort (key = len) # The key value is the print ll function that is always called.
print sorted("Sorting1234", key=lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x.islower(), x))#['g', 'i', 'n', 'o', 'r', 't', 'S', '1', '3', '2', '4']
3. Anonymous function lambda
# Lambda parameters: Return Value lambda x: x + 1
4... for... in... if...
a = [1,2,3]print [i**2 for i in a if i>0]
5. filter map reduce
Filter (function, sequence): Execute function (item) in sequence for items in sequence, and combine items whose execution result is True into a List/String/Tuple (depending on the sequence type) to return
print filter( lambda x:x!='a', 'abcd' ) #'bcd'
Map (function, sequence): Execute function (item) in sequence for items in sequence. See the execution result to form a List and return:
print map( lambda x:x+1, range(3) ) #[1,2,3]
Reduce (function, sequence, starting_value): calls the function sequentially for items in sequence. If starting_value exists, it can also be called as an initial value. For example, it can be used to sum the List.
print reduce( lambda x,y:x+y, range(3), 10 ) #13
6. generator
a = (x * x for x in range(3))for i in a:print i
7. range (starting, ending, incremental)
print range(1,9,2) #[1, 3, 5, 7]
8 ....?... :...
(1) variable = a if expression else B # completely equivalent (2) variable = (expression and [B] or [c]) [0] (3) variable = expression and B or c # is not completely equivalent. B cannot be False.
F