A collection of special Python programming tips

Python as an advanced editing language, there are many tips to use.

1. Swap variable values

a = 0b = 1a,b = b, a
Copy the code

2. Continuous assignment

a, b = 2, 1
Copy the code

3, automatic unpack assignment

A, b, c, d = 1 and 4, 'domi aa, * others = [1, 4,' domi] > > > others [3, 4, 'domi]Copy the code

4. Chain comparison

Print ('Hello world') # equivalent if 5<= a and a <= 15: print('Hello world')Copy the code

Repeat lists

a = [1,'domi']*2>>> a[1, 'domi', 1, 'domi']
Copy the code

6. Repeated strings

>>> a[1]*2'domidomi'
Copy the code

7. Triadic operation

A = 10b = True if a==10 else False>>> bTrue is equivalent to if a==10: b = Trueelse: b = FalseCopy the code

8. Dictionary merge

a = {"a":1}b = {"b":2}>>> {**a, **b}{'a': 1, 'b': 2}
Copy the code

9. String inversion

s = "domi"s1 = s[::-1]
Copy the code

10. List to string

s = ['d','o','m','i']s1 = "".join(s)>>> s1'domi'
Copy the code

11. Dictionary derivation

a = {x:x**2 for x in range(3)}>>> a{0: 0, 1: 1, 2: 4}
Copy the code

12, dictionary key and value interchangeable

a_dict = {'a': 1, 'b': 2, 'c': 3}{value:key for key, value in a_dict.items()}{1: 'a', 2: 'b', 3: 'c'}
Copy the code

13. Use counter to find the most common element in the list

A = [1,2,3,3,0]from collections import Counterb = Counter(a) b.ost_common (1)[(3, 2)] # 3Copy the code

14, assignment expression, : =, can be variable assignment and expression on a line

import res ="helloworld"match = re.search('o', s)if match:    num = match.group(0)else:    num = Nonenum
Copy the code

3 and 4 can be combined into one line of code

if match := re.search('o', s):    num = match.group(0)else:    num = None
Copy the code

15. The isintance function is used to judge the instance type

A = 1.2isinstance(a, (int, float)) b = "STR "isinstance(a, int)Copy the code

16, check whether a string begins or endswith a character, startswith,endswith

s = "123asdz"s.startswith("1")
s.endswith(("z","a"))
Copy the code

HTTP. Server share files

python3 -m http.server
Copy the code

The effect is as follows: easy to share file directories in the browser, easy to share files on the LAN

 

18. Find the most frequent number in the list

A =,2,3,3,0 [1] Max (set) (a), the key = a.c mount)Copy the code

19. Expand the list

a.extend(['domi','+1'])>>> a[1, 2, 3, 3, 0, 'domi', '+1']
Copy the code

20, list negative index

a[-2]'domi'
Copy the code

21. List Slices,

A = [1, 2, 3, 'domi', 'mi'] > > > [then] # extract a third to fifth position () does not contain the fifth position data [3, 'domi] > > > a [3] : # before extracting data [1, 2, 3 3] > > > a [2] : : # extract even term [1, 3, 'mi'] > > > a [1:2] # extract odd term [2, 'domi] > > > a list] [: : - 1 # inversion [' mi', 'domi, 3, 2, 1]Copy the code

22. Turn a two-dimensional array into a one-dimensional array

The import itertoolsa = [[1, 2], [3, 4], [5, 6]] b = itertools. Chain (* a) > > > the list (b) [1, 2, 3, 4, 5, 6]Copy the code

23. Iteration with index

A = ['d',' O ','m',' I ']for index, value in enumerate(a): print(' %d = %s' %(index, value)) print(' %d = % S '%(index, value)Copy the code

24. List derivation

a = [x*3 for x in range(3)]>>> a[0, 3, 6]a = [x*3 for x in range(10) if x%2 == 0]>>> a[0, 6, 12, 18, 24]
Copy the code

Generator expressions

ge = (x*2 for x in range(10))>>> ge<generator object <genexpr> at 0x000001372D39F270>>>> next(ge)0>>>>>> next(ge)2>>> next(ge)4>>> next(ge)6>>> next(ge)8>>> next(ge)10>>> next(ge)12>>> next(ge)14>>> next(ge)16>>> next(ge)18>>> next(ge) # Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIterationCopy the code

26. Set derivation

>>> nums = {n**2 for n in range(10)}>>> nums{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
Copy the code

27. Check whether the key is in the dictionary

>>> d = {"1":"a"}>>> d['2']Traceback (most recent call last):  File "<stdin>", line 1, in <module>KeyError: '2'>>> d['1']'a'>>> '1' in dTrue>>> '2' in dFalse>>> d.get('1')'a'>>> d.get('2')
Copy the code

28. Open the file

with open('foo.txt', 'w') as f:    f.write("hello world")
Copy the code

29. Two lists are combined to form a dictionary

A = ["One","Two","Three"]b = [1,2,3]dictionary = dict(zip(a, b))print(dictionary)Copy the code

30. Remove duplicate elements from the list

​​​​​​​

,4,1,8,2,8,4,5 my_list = [1] my_list = list (set (my_list))Copy the code

31. Print your calendar

import calendar

>>> print(calendar.month(2021, 1))    January 2021Mo Tu We Th Fr Sa Su             1  2  3 4  5  6  7  8  9 1011 12 13 14 15 16 1718 19 20 21 22 23 2425 26 27 28 29 30 31
Copy the code

32. Anonymous functions

Def add(a, b): return a+b# = lambda a,b:a+badd(1,2)Copy the code