A note for myself to remember some Python coding tips.
1. String to char array 1 2 3 s = 'python coding tips' arr = list (s) print (arr)
Output:
1 ['p', 'y', 't', 'h', 'o', 'n', ' ', 'c', 'o', 'd', 'i', 'n', 'g', ' ', 't', 'i', 'p', 's']
2. Using enumerate 1 2 3 arr = ['a' , 'b' , 'c' ] for i, v in enumerate (arr): print (i,v)
Output:
1 2 3 (0, 'a') (1, 'b') (2, 'c')
3. Are strings/lists/tuples empty According to the answer from Stack Overflow , this is a good coding style.
1 2 3 4 5 6 7 l = ['' , (), [1 , 2 ]] for i, v in enumerate (l): if v: print (f'element {i} is not empty' ) else : print (f'element {i} is empty' )
Output:
1 2 3 element 0 is empty element 1 is empty element 2 is not empty
4. Create all 0 list 1 2 3 4 5 arr = [0 ] * 10 print (arr)arr[1 ] = 1 print (arr)
Output:
1 [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
5. Lambda function A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. Syntax
1 lambda [arguments] : [expression]
Examples:
1 2 3 4 5 f = lambda a : a + 10 print (f(5 ))g = lambda a, b : a * b print (g(5 , 6 ))
Output:
6. Sorting Use either sort
or sorted
function.
sort
will sort element in the list
sorted
will return a new sorted list
Function sorted
can take a maxinum of three parameters:
iteralbe: A sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator
reverse: Default to False
for ascending order. Set it to be True
for descending order
key: A function that serves as a key for the sort comparison. Defaults to None
1 2 3 4 5 6 7 8 9 fruits = ["apple" , "banana" , "pear" ] print (sorted (fruits, key=len ))l = [[2 ,3 ], [0 , 5 ], [4 , 1 ]] def pick_second (x ): return x[1 ] print (sorted (l, key=pick_second, reverse=True ))print (sorted (l, key=lambda x : x[1 ], reverse=True ))
Output:
1 2 3 ['pear', 'apple', 'banana'] [[0, 5], [2, 3], [4, 1]] [[0, 5], [2, 3], [4, 1]]
7. Heap Simple usage of heap in Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 from heapq import heapify, heappush, heappopheap = [] heapify(heap) heappush(heap, 10 ) heappush(heap, 30 ) heappush(heap, 20 ) heappush(heap, 400 ) print (f'Head value of heap : {heap[0 ]} ' )while heap: print (heappop(heap))
Output:
1 2 3 4 5 Head value of heap : 10 10 20 30 400
Control heap compare with tuple.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from heapq import heapify, heappush, heappopheap = [] heapify(heap) intervals = [[0 ,30 ],[5 ,10 ],[15 ,20 ],[7 ,17 ]] def second_element (ele ): return ele[1 ] for i, interval in enumerate (intervals): heappush(heap, (second_element(interval), interval)) while heap: print (heappop(heap)[1 ])
Output:
1 2 3 4 [5, 10] [7, 17] [15, 20] [0, 30]
8. int range The int type in Python 3, equivalent to the long type in Python 2, has no max or min limit.
Before
Now
Min
-2^31
-2^63
Max
2^31-1
2^63-1
9. List manipulation 1 2 3 4 5 l = [1 , 2 , 3 , 4 , 5 , 4 , 3 , 2 , 1 ] l.index(2 ) l.pop() l.pop(0 ) l.insert(0 , 1 )
10. Reverse list in-place 1 2 3 4 5 6 7 nums = [1 , 2 , 3 , 5 , 7 ] nums[:] = nums[::-1 ] print (nums) index = 2 a[:] = a[:index+1 ] + a[index+1 :][::-1 ] print (nums)
11. Tree in order traversal left -> root > right preorder traversal root -> left -> right postorder traversal left -> right -> root
Author:
Lufan Li
Permalink:
https://lufan.io/2022/09/20/python-coding-tips/
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE