Python's 22 programming skills, please accept!

1. Exchange two digits in situ

Python provides an intuitive way to assign and exchange (variable values) in a single line of code. See the following example:

x,y= 10,20

print(x,y)

x,y= y,x

print(x,y)

#1 (10, 20)

#2 (20, 10)

A new tuple is formed on the right side of the assignment and unpack on the left side to the variables < a > and < B >.

Once the assignment is completed, the new tuple becomes unreferenced and marked as garbage collectable, eventually completing the exchange of variables.

 

2. Chain comparison operator

Aggregation of comparison operators is another sometimes convenient technique:

n= 10

result= 1< n< 20

print(result)

# True

result= 1> n<= 9

print(result)

# False

 

3. Conditional assignment using ternary operators

The ternary operator is a shortcut to the if-else statement, that is, the conditional operator:

[The expression is a true return value] if [expression] else [expression is a false return value]

Here are some examples that you can use to make your code compact and concise. The following statement says, "If y is 9, assign 10 to x, or assign 20 to x." We can also extend the chain if necessary.

x = 10 if (y == 9) else 20

Similarly, we can do this for classes:

x = (classA if y == 1 else classB)(param1, param2)

In the example above, classA and classB are two classes, and the constructor of one class is called.

Here is another example where multiple conditional expressions are linked together to calculate the minimum value:

def small(a,b,c):

returnaifa<= banda<= celse(bifb<= aandb<= celsec)

print(small(1,0,1))

print(small(1,2,2))

print(small(2,2,3))

print(small(5,4,3))

#Output

#0 #1 #2 #3

We can even use ternary operators in list derivation:

[m**2 if m > 10 else m**4 for m in range(50)]

#=> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

 

4. Multi-line strings

The basic way is to use backslashes from C:

multiStr= "select * from multi_row

where row_id < 5"

print(multiStr)

# select * from multi_row where row_id < 5

Another technique is to use three quotes:

multiStr= """select * from multi_row

where row_id < 5″""

print(multiStr)

#select * from multi_row

#where row_id < 5

The common problem with the above methods is the lack of appropriate indentation, which inserts spaces in strings if we try to indent. So the final solution is to divide the string into multiple lines and enclose the entire string in parentheses:

multiStr= ("select * from multi_row "

"where row_id < 5 "

"order by age")

print(multiStr)

#select * from multi_row where row_id < 5 order by age

 

5. Store list elements into new variables

We can use lists to initialize multiple variables. When parsing lists, the number of variables should not exceed the number of elements in the list.

testList= [1,2,3]

x,y,z= testList

print(x,y,z)

#-> 1 2 3

 

6. File Path of Printing Introducing Module

If you want to know the absolute path to the module referenced in the code, you can use the following techniques:

import threading

import socket

print(threading)

print(socket)

#1- <module 'threading' from '/usr/lib/python2.7/threading.py'>

#2- <module 'socket' from '/usr/lib/python2.7/socket.py'>

 

7. The operator in an interactive environment

This is a useful feature that most of us don't know. In the Python console, whenever we test an expression or call a method, the result is assigned to a temporary variable: (an underscore).

>>> 2+ 1

3

>>> _

3

>>> print_

3

"" is the output of the last expression executed.

 

8. Dictionary/Set Derivation

Similar to the list deduction we use, we can also use dictionary/set deduction, which is simple and effective. Here is an example:

testDict= {i: i *iforiinxrange(10)}

testSet= {i *2foriinxrange(10)}

print(testSet)

print(testDict)

#set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])

#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Note: There is only one difference between the two statements <: >. In addition, when running the above code in Python 3, change < xrange > to < range >.

 

9. Debugging scripts

We can set breakpoints in Python scripts with the help of the <pdb> module. Here is an example:

import pdb

pdb.set_trace()

We can specify <pdb.set_trace()> anywhere in the script and set a breakpoint there, which is quite simple.

 

10. Open file sharing

Python allows you to run an HTTP server to share files from the root path. Here is the command to open the server:

# Python 2

python -m SimpleHTTPServer

# Python 3

python3 -m http.server

The above command will open a server at the default port of 8000. You can pass a custom port number to the above command in the form of the last parameter.

 

11. Check the objects in Python

We can check objects in Python by calling dir(). Here is a simple example:

test= [1,3,5,7]

print(dir(test))

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

 

12. Simplify if statements

We can validate multiple values in the following way:

if m in [1,3,5,7]:

Instead of:

if m==1 or m==3 or m==5 or m==7:

Or we can use'{1,3,5,7}'instead of'[1,3,5,7]' for in operators, because the element in set is O(1) operation.

 

13. A line of code calculates the factorial of any number

Python 2.x.

result= (lambdak: reduce(int.__mul__,range(1,k+1),1))(3)

print(result)

#-> 6

Python 3.x.

import functools

result= (lambdak: functools.reduce(int.__mul__,range(1,k+1),1))(3)

print(result)

#-> 6

 

14. Find the most frequent number in the list

test= [1,2,3,4,2,2,3,1,4,4,4]

print(max(set(test),key=test.count))

#-> 4

 

15. Reset recursive restrictions

Python limits the number of recursions to 1000, and we can reset this value:

import sys

x=1001

print(sys.getrecursionlimit())

sys.setrecursionlimit(x)

print(sys.getrecursionlimit())

#1-> 1000

#2-> 1001

Please use the above techniques only when necessary.

 

16. Check the memory usage of an object

In Python 2.7, a 32-bit integer takes up 24 bytes and 28 bytes in Python 3.5. To determine memory usage, we can call the getsizeof method:

In Python 2.7

import sys

x=1

print(sys.getsizeof(x))

#-> 24

In Python 3.5

import sys

x=1

print(sys.getsizeof(x))

#-> 28

 

17. Use _slots_ to reduce memory overhead

Have you noticed that your Python application takes up a lot of resources, especially memory? One trick is to use _slots_ variables to reduce memory overhead to some extent.

import sys

classFileSystem(object):

def __init__(self,files,folders,devices):

self.files= files

self.folders= folders

self.devices= devices

print(sys.getsizeof(FileSystem))

classFileSystem1(object):

__slots__= ['files','folders','devices']

def __init__(self,files,folders,devices):

self.files= files

self.folders= folders

self.devices= devices

print(sys.getsizeof(FileSystem1))

#In Python 3.5

#1-> 1016

#2-> 888

Obviously, you can see from the results that memory usage savings do exist, but you should only use _slots_ when the memory overhead of a class is unnecessary. Use it only after performance analysis of the application, otherwise you just make the code hard to change without real benefits.

Translator's Note: In my win10 Python 2.7, the results above are:

#In Python 2.7 win10

#1-> 896

#2-> 1016

Therefore, this method of comparison is not so convincing. The main purpose of using _slots_ is to restrict the attribute information of the object. In addition, when generating many objects, the cost may be less. See python official documents for details:

The slots declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because dict is not created for each instance. ]

 

18. Use lambda to mimic the output method

import sys

lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))

lprint("python","tips",1000,1001)

#-> python tips 1000 1001

 

19. Building a dictionary from two related sequences

t1= (1,2,3)

t2= (10,20,30)

print(dict(zip(t1,t2)))

#-> {1: 10, 2: 20, 3: 30}

 

20. Search for multiple prefixes of strings in one line of code

print("http://www.google.com".startswith(("http://","https://")))

print("http://www.google.co.uk".endswith((".com",".co.uk")))

#1-> True

#2-> True

 

21. Construct a list without using loops

import itertools

test= [[-1,-2],[30,40],[25,35]]

print(list(itertools.chain.from_iterable(test)))

#-> [-1, -2, 30, 40, 25, 35]

 

22. Implement a true switch-case statement in Python

The following code uses a dictionary to simulate the construction of a switch-case.

def xswitch(x):

returnxswitch._system_dict.get(x,None)

xswitch._system_dict= {'files': 10,'folders': 5,'devices': 2}

print(xswitch('default'))

print(xswitch('devices'))

#1-> None

#2-> 2

Keywords: Python socket Lambda Google

Added by jdeer0618 on Fri, 17 May 2019 05:37:59 +0300