Python Common Code
Frequently used python code
Python Quick Start
Ternary operator
1 | p_max_count = len(i['prompt']) if p_max_count < len(i['prompt']) else p_max_count |
Calculate time spent
1 | import datetime |
Random
Int
1 | import random |
Sort
Sort 2D list
1 | employees = [[10, 'Jack', 1997], [3, 'Jack', 1998], [8, 'Smith', 2001]] |
Sort dictionary
1 | dic = {2: 56, 1: 2, 7: 12, 4: 24, 5: 12, 3: 323} |
Reverse
1 | a = "54321" |
List
List generator
1 | a = [1, 2, 3, 4, 5, 6] |
For
For-Else
The only way that the code would run to “else”, is that there is no break in the for-loop.
1 | for item in container: |
String
Case
1 | a = "String" |
Component
1 | a = "123asJIjg" |
Initilization
Dictionary
1 | x = dict.fromkeys(['A', 'B', 'C'], 0) |
Simplify
Dictionary Count
1 | if char not in unigram_counts: |
Visualization
Matplotlib
1 | import matplotlib.pyplot as plt |
Draw by one list
1 | import matplotlib.pyplot as plt |
Draw by two list
1 | import matplotlib.pyplot as plt |