Hello everyone, it is said that the method of chasing girls is greater than the attitude, learning Python is also, today I will share with you are some of the tips I commonly used when writing programs in Python.
1. Print the same character multiple times
In Python, you don't have to write a function to print the same character over and over again, you can just use Print.
tem = 'I Love Python ' print(tem * 3) I Love Python I Love Python I Love Python
2. Use generators inside functions
When writing Python programs, we can use generators directly inside functions, which makes the code more concise.
sum(i for i in range(100) )
3. Assigning list variables
In Python we can divide the values of a list into custom variables so that we can print the values of the list in any desired order.
List = ["I","Love","Python"] a, b, c = List print(a,b,c ) #I Love Python print(c,b,a ) #Python Love I
4. Check memory usage
In Python we can use the built-in module sys to check how much memory each variable takes up, as you can see from the code below, strings of different lengths consume different amounts of memory.
import sys a, b, c,d = "I" ,"Love", "Python", 2020 print((a)) #50 print((b)) #53 print((c)) #55 print((d)) #28
5. List reversal
There are many ways to reverse a list in Python, here are the two that I commonly use
# Method 1 List = ["I","Love","Python"] () print(List) #['Python', 'Love', 'I'] # Method 2 List = ["I","Love","Python"] List = List[::-1] print(List) #['Python', 'Love', 'I']
6. Exchange of variables
In some programming languages, exchanging two variables generally requires the use of temporary variables, whereas in Python, a single line of code is sufficient
a,b = 'zaoqi' , 'Python' a,b = b,a
7. Combined strings
In Python, we can easily combine strings in a list
List = ['I ', 'Love ', 'Python'] print(''.join(List)) #I Love Python
8. Convert nested lists
In Python, we can convert nested lists to lists with a single line of code using Itertools
import itertools List = [[1, 2], [3, 4], [5, 6]] print(list(.from_iterable(List))) #[1, 2, 3, 4, 5, 6]
9. Transpose Matrix
In Python, we can transpose matrices by using the zip function. Note that in Python 3 you also need to convert the result to a list.
matrix = [[1, 2, 3], [4, 5, 6]] print(list(zip(*matrix))) #[(1, 4), (2, 5), (3, 6)]
10. Compare Lists
In Python, we can take the intersection and difference of lists to compare the similarities and differences of elements in two lists.
a = ['I', 'Love', 'Python'] b = ['I', 'Love', 'python'] print(set(a).difference(set(b))) print(set(a).intersection(b)) #{'Python'} #{'Love', 'I'}
Above is the commonly used 10 Python practical tips in detail, more information about Python practical tips please pay attention to my other related articles!