Here are a few tips when working with python, hopefully it will help your work
Swap the values of two variables:
1 2 3 4 5 | a, b = 10 print(a, b) a, b = b, a print(a, b) |
Create a string from all the elements in the list:
1 2 3 | list = ["Make", "F33", "Great", "Again"] print(" ",join(list)) |
Find the value that appears the most in the array:
1 2 3 4 5 6 7 8 9 10 | Cách 1: array = [1,2,3,1,2,3,2,2,4,5,1] most_frequent = max(set(array, key=array.count)) print(most_frequent) Cách 2: from collections import Counter as cnt most_frequent = cnt(a).most_common(3) print(most_frequent) |
Reverse a string:
1 2 3 4 5 6 7 8 9 10 | string_origin = 'python' Cách 1: string_reverse = string_origin[::-1] print(string_reverse) Cách 2: for char in reversed(string_origin): print(char) |
Reverse a list:
1 2 3 4 5 6 7 8 9 | list = ["awesome", "is", "python"] Cách 1: print(list[::-1]) Cách 2: for element in reversed(list): print(element) |
Find the displacement matrix of a 2-dimensional array:
1 2 3 4 | array_2d = [['a', 'b'], ['c', 'd'], ['e', 'f']] matrix_transpose = zip(*array_2d) print(matrix_transpose) |
Chained Comparison:
1 2 3 4 | number = 10 print(5<number<20) print(1==number<20) |
Chained function call:
Depending on the condition, different functions will be called, but these two functions must have the same parameters.
1 2 3 4 5 6 7 8 9 | def product(a, b): return a+b def add(a, b): return a+b condition = True print((product if condition else add)(10, 10)) |
Copy a list:
1 2 3 4 5 6 7 8 9 | array = [1,2,3,4,5,6] array_copy = array.copy() print(array_coppy) from copy import deepcopy list = [[1,2], [3,4]] list_copy = deepcopy(list) print(list_copy) |
Sort values in dictionary by value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | dictionary = {'apple':1, 'orange':20, 'lemon':5, 'coconut': 10} Cách 1: dict_sorted = sorted(dictionary.items(), key=lambda x: x[1]) print(dict_sorted) Cách 2: from operator import itemgetter dict_sorted = sorted(dictionary.items(), key=itemgetter[1]) print(dict_sorted) Cách 3: dict_sorted = sorted(dictionary, key=dictionary.get) print(dict_sorted) |
For else
1 2 3 4 5 6 7 | array = [1,2,3,4,5,6] for item in array: if item == 0: break else: print("did not break out of for loop ") |
Include dictionary:
1 2 3 4 5 6 7 8 9 10 | dic_1 = {a:1} dic_2 = {b:3} print(**dic_1, **dic_2) print(dict(dic_1.item() | dic_2.item() )) another way: dic_1.update(dict_2) print(dict_1) |
And there are many more tips, readers can check out here https://github.com/brennerm/PyTricks