Direct exchange of two digits
Python provides an intuitive way to assign and exchange (variable values) in a line of code. As follows:
x, y = 10, 20 print(x, y) x, y = y, x print(x, y) #1 (10, 20) #2 (20, 10)
In the above code, a new tuple is formed on the right side of the assignment, while the unreferenced tuple is immediately unpacked to the name on the left side.And.
When the assignment is completed, the new tuple becomes unreferenced and marked as garbage collectable, resulting in digital switching.
Link comparison operator
Aggregation of comparison operators is another technique that is sometimes easy to use.
n = 10 result = 1 < n < 20 print(result) # True result = 1 > n <= 9 print(result) # False
Conditional assignment using ternary operators
The ternary operator is a fast operation of if-else statements (that is, conditional operators):
[on_true] if [expression] else [on_false]
Here are two examples to show how you can use this technique to make your code more compact and concise.
The following sentence means "If y is 9, assign 10 to x, otherwise assign 20 to x". If necessary, we can extend this operator link:
x = 10 if (y == 9) else 20
Similarly, we can operate on class objects like this:
x = (classA if y == 1 else classB)(param1, param2)
In the above example, classA and classB are two classes, and one of the class constructors is called.
Using multiline strings
This method uses backslashes derived from C language:
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
A common problem with the above method is the lack of appropriate indentation, and if we want to indent, we insert spaces into the string.
So the final solution is to divide the string into multiple lines and enclose the whole 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
Save the elements of a list into a new variable
We can use a list to initialize multiple variables. When parsing the list, the number of variables should not exceed the number of elements in the list, otherwise errors will be reported.
testList = [1,2,3] x, y, z = testList print(x, y, z) #-> 1 2 3
Print out the file path of the imported module
If you want to know the absolute path of the module imported in the code, use the following technique:
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'>
Use the interactive "" operator
In fact, this is a very useful function, but many of us have not noticed it.
In the Python console, whenever we test an expression or call a function, the result is assigned a temporary name, (an underscore).
>>> 2 + 1 3 >>> _ 3 >>> print _ 3
Here "" is the result of the last expression executed.
Dictionary/Set Derivation
Just as we use list expressions, we can also use dictionary / set inference. Very simple to use and very effective, examples are as follows:
testDict = {i: i * i for i in xrange(10)} testSet = {i * 2 for i in xrange(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, if you want to run the above code with Python 3, replace < xrange > with < range >.
Debugging scripts
We can use the < PDB > module to set breakpoints in Python scripts, as follows:
import pdb pdb.set_trace()
We can specify <pdb.set_trace()> anywhere in the script, and then set a breakpoint there, which is very convenient.
Setting up file sharing
Python allows us to run HTTP servers, which can be used to share files in the server root directory. The command to start the server is as follows:
# Python 2: python -m SimpleHTTPServer # Python 3: python3 -m http.server
The above command will start a server on the default port 8000. You can also use the custom port to pass the port as the last element into the above command.
Check objects in Python
We can check objects in Python by calling the dir() method. 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']
Simplified if statement
We can validate multiple values in the following way:
if m in [1,3,5,7]:
Instead of this:
if m==1 or m==3 or m==5 or m==7:
For the in operator, we can also use'{1,3,5,7}'instead of'[1,3,5,7]', because'set' can get each element through O(1).
Detecting Python versions at runtime
Sometimes we may not want to execute programs if the current Python runs below the supported version. Then you can use the following code script to detect the version of Python. It can also print out the current Python version in readable format.
import sys #Check the Python version currently in use if not hasattr(sys, "hexversion") or sys.hexversion != 50660080: print("Sorry, you aren't running on Python 3.5\n") print("Please upgrade to 3.5.\n") sys.exit(1) #Print out the Python version in readable format print("Current Python version: ", sys.version) //In addition, you can replace sys.hexversion!= 50660080 with sys. version_info >= (3, 5).
Running in Python 2.7, the output is:
Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux Sorry, you aren't running on Python 3.5 Please upgrade to 3.5.
Run the output in Python 3.5 as follows:
Python 3.5.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05) [GCC 5.3.0]
Combining multiple strings
If you want to splice all token s in the list, look at the following examples to see:
>>> test = ['I', 'Like', 'Python', 'automation']
Now let's create a string from the elements in the list above:
>>> print ''.join(test)
Four ways to flip strings/lists
#Flip the list itself testList = [1, 3, 5] testList.reverse() print(testList) #-> [5, 3, 1] #Flip in iteration in a loop for element in reversed([1,3,5]): print(element) #1-> 5 #2-> 3 #3-> 1 #Flipping strings in a line of code "Test Python"[::-1]
We will get the result "nohtyP tseT".
#Flip a list with slices [1, 3, 5][::-1]
The above command will get the output [5, 3, 1].
Use enumeration
Using enumerations, it is easy to find indexes in loops:
testlist = [10, 20, 30] for i, value in enumerate(testlist): print(i, ': ', value) #1-> 0 : 10 #2-> 1 : 20 #3-> 2 : 30 //Use enumerations in Python //We can create enumeration definitions in the following ways: class Shapes: Circle, Square, Triangle, Quadrangle = range(4) print(Shapes.Circle) print(Shapes.Square) print(Shapes.Triangle) print(Shapes.Quadrangle) #1-> 0 #2-> 1 #3-> 2 #4-> 3
Returns multiple values from a function
There are not many programming languages to support this function, however, functions in Python can return multiple values.
Refer to the following examples to see how it works:
# Functions that return multiple values def x(): return 1, 2, 3, 4 # Call the above function a, b, c, d = x() print(a, b, c, d) #-> 1 2 3 4
Decompression of function parameters using * operators
Operators provide an artistic way to decompress parameter lists. See the following example:
def test(x, y, z): print(x, y, z) testDict = {'x': 1, 'y': 2, 'z': 3} testList = [10, 20, 30] test(*testDict) test(**testDict) test(*testList) #1-> x y z #2-> 1 2 3 #3-> 10 20 30
Use dictionaries to store expressions
stdcalc = { 'sum': lambda x, y: x + y, 'subtract': lambda x, y: x - y } print(stdcalc['sum'](9,3)) print(stdcalc['subtract'](9,3)) #1-> 12 #2-> 6
A line of code calculates the factorial of any number
# Python 2.X result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3) print(result) #-> 6 # Python 3.X import functools result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3) print(result) #-> 6
Find the most frequent value in the list
test = [1,2,3,4,2,2,3,1,4,4,4] print(max(set(test), key=test.count)) #-> 4 //Reset recursive restriction Python Limiting recursion to 1000, we can reset this value: import sys x=1001 print(sys.getrecursionlimit()) sys.setrecursionlimit(x) print(sys.getrecursionlimit()) #1-> 1000 #2-> 1001
Tip: Use this technique when necessary.
Check memory usage of an object
In Python 2.7, a 32-bit integer value takes 24 bytes, while in Python 3.5 it takes 28 bytes. We can call methods to verify memory usage.
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
Use _slots_to reduce memory consumption
I wonder if you've noticed that your Python program takes up a lot of resources, especially memory? Here's a trick to use < slots > class variables to reduce memory consumption.
import sys class FileSystem(object): def __init__(self, files, folders, devices): self.files = files self.folders = folders self.devices = devices print(sys.getsizeof( FileSystem )) class FileSystem1(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, some memory savings can be seen from the layoffs. However, this method should be used when the memory footprint of a class is too large to be necessary. Use it after performance analysis of the application, otherwise it won't do any good except make the code difficult to change.
Using Ramda to imitate the output method
import sys lprint=lambda *args:sys.stdout.write(" ".join(map(str,args))) lprint("python", "tips",1000,1001) #-> python tips 1000 1001
Create 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}
Search for prefixes and suffixes of strings with 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
Construct a list without using any loops
import itertools test = [[-1, -2], [30, 40], [25, 35]] print(list(itertools.chain.from_iterable(test))) #-> [-1, -2, 30, 40, 25, 35]
If there is an embedded list or tuple in the input list as an element, the following method is used, but there is a limitation. It uses a for loop:
def unifylist(l_input, l_target): for it in l_input: if isinstance(it, list): unifylist(it, l_target) elif isinstance(it, tuple): unifylist(list(it), l_target) else: l_target.append(it) return l_target test = [[-1, -2], [1,2,3, [4,(5,[6,7])]], (30, 40), [25, 35]] print(unifylist(test,[])) #Output => [-1, -2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35]
Implementing a true switch-case statement in Python
Here's a code example that uses a dictionary to mimic a switch-case construct:
What I don't know in the process of learning can be added to me? python learning communication deduction qun, 784758214 There are good learning video tutorials, development tools and e-books in the group. Share with you the current talent needs of python enterprises and how to learn python from zero foundation, and what to learn def xswitch(x): return xswitch._system_dict.get(x, None) xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2} print(xswitch('default')) print(xswitch('devices')) #1-> None #2-> 2
epilogue
Hopefully, the Python tips and suggestions listed above will help you complete Python development quickly and efficiently and apply them to projects.