(封面是二乔~99岁生日快乐呀老头子~(≧▽≦)/~)
转载自 https://www.tutorialspoint.com/10-interesting-python-cool-tricks
With increase in popularity of python, more and more features are becoming available for python coding. Using this features makes writing the code in fewer lines and cleaner. In this article we will see 10 such python tricks which are very frequently used and most useful.
1. Reversing a List 反转列表
We can simply reverse a given list by using a reverse() function. It handles both numeric and string data types present in the list.
Example1
2
3List = ["Shriya", "Lavina","Sampreeti" ]
List.reverse()
print(List)
Output
Running the above code gives us the following result −1
['Sampreeti', 'Lavina', 'Shriya']
2. Print list elements in any order 以任意顺序打印列表元素
If you need to print the values of a list in different orders, you can assign the list to a series of variables and programmatically decide the order in which you want to print the list.
Example1
2
3
4List = [1,2,3]
w, v, t = List
print(v, w, t )
print(t, v, w )
Output
Running the above code gives us the following result −1
2(2, 1, 3)
(3, 2, 1)
3. Using Generators Inside Functions 使用生成器
We can use generators directly inside a function to writer shorter and cleaner code. In the below example we find the sum using a generator directly as an argument to the sum function.
Example1
sum(i for i in range(10) )
Output
Running the above code gives us the following result −1
45
4. Using the zip() function
When we need to join many iterator objects like lists to get a single list we can use the zip function. The result shows each item to be grouped with their respective items from the other lists.
Example1
2
3
4Year = (1999, 2003, 2011, 2017)
Month = ("Mar", "Jun", "Jan", "Dec")
Day = (11,21,13,5)
print zip(Year,Month,Day)
Output
Running the above code gives us the following result −1
[(1999, 'Mar', 11), (2003, 'Jun', 21), (2011, 'Jan', 13), (2017, 'Dec', 5)]
5. Swap two numbers using a single line of code 交换
Swapping of numbers usually requires storing of values in temporary variables. But with this python trick we can do that using one line of code and without using any temporary variables.
Example1
2
3
4
5
6x,y = 11, 34
print x
print y
x,y = y,x
print x
print y
Output
Running the above code gives us the following result −1
2
3
411
34
34
11
6. Transpose a Matrix 转置矩阵
Transposing a matrix involves converting columns into rows. In python we can achieve it by designing some loop structure to iterate through the elements in the matrix and change their places or we can use the following script involving zip function in conjunction with the * operator to unzip a list which becomes a transpose of the given matrix.
Example1
2
3
4x = [[31,17],
[40 ,51],
[13 ,12]]
print (zip(*x))
Output
Running the above code gives us the following result −1
[(31, 40, 13), (17, 51, 12)]
*可以理解为“解包”,即将列表中的元素取出来操作
zip
wants a bunch of arguments to zip together, but what you have is a single argument (a list, whose elements are also lists). The in a function call “unpacks” a list (or other iterable), making each of its elements a separate argument. So without the , you’re doing zip( [[1,2,3],[4,5,6]] ). With the *, you’re doing zip([1,2,3], [4,5,6])
7. Print a string N Times 打印一个字符串n次
The usual approach in any programming language to print a string multiple times is to design a loop. But python has a simple trick involving a string and a number inside the print function.
Example1
2str ="Point";
print(str * 3);
Output
Running the above code gives us the following result −1
PointPointPoint
8. Reversing List Elements Using List Slicing 使用切片翻转列表元素
List slicing is a very powerful technique in python which can also be used to reverse the order of elements in a list.
Example1
2
3
4
5
6
7#Reversing Strings
list1 = ["a","b","c","d"]
print list1[::-1]
# Reversing Numbers
list2 = [1,3,6,4,2]
print list2[::-1]
Output
Running the above code gives us the following result −1
2['d', 'c', 'b', 'a']
[2, 4, 6, 3, 1]
切片[开始:结束:步长]1
2
3
4
5
6
7
8
9
10
11
12
13
14print(a)
[ 0.64061262 0.8451399 0.965673 0.89256687 0.48518743]
print(a[-1]) ###取最后一个元素
[0.48518743]
print(a[:-1]) ### 除了最后一个取全部
[ 0.64061262 0.8451399 0.965673 0.89256687]
print(a[::-1]) ### 取从后向前(相反)的元素
[ 0.48518743 0.89256687 0.965673 0.8451399 0.64061262]
print(a[2::-1]) ### 取从下标为2的元素翻转读取
[ 0.965673 0.8451399 0.64061262]
9. Find the Factors of a Number 找因子
When we are need of the factors of a number, required for some calculation or analysis, we can design a small loop which will check the divisibility of that number with the iteration index.
Example1
2
3
4
5f = 32
print "The factors of",x,"are:"
for i in range(1, f + 1):
if f % i == 0:
print(i)
Output
Running the above code gives us the following result −1
2
3
4
5
6
7The factors of 32 are:
1
2
4
8
16
32
10. Checking the Usage of Memory 检查存储占用
We can check the amount of memory consumed by each variable that we declare by using the getsizeof() function. As you can see below, different string lengths will consume different amount of memory.
Example1
2
3
4
5
6import sys
a, b, c,d = "abcde" ,"xy", 2, 15.06
print(sys.getsizeof(a))
print(sys.getsizeof(b))
print(sys.getsizeof(c))
print(sys.getsizeof(d))
Output
Running the above code gives us the following result −1
2
3
438
35
24
24