All of these tips can help you compress your code and optimize your operation. In addition, you can easily use them in real projects in your daily work.
Tip # # #. Exchange two numbers in situ
Python provides an intuitive way to assign values and exchanges (variable values) in a single line of code, see the following example:
X, y = ten, 20print (x, y) x, y = y, xprint (x, y) #1 (Ten) #2 (20, 10)
The right side of the assignment forms a new tuple, and the left side immediately resolves (unpack) that (unreferenced) tuple to variable <a> and <b>.
Once the assignment is complete, the new tuple becomes an unreferenced state and is marked as garbage-collected, and eventually the variable is exchanged.
Tips. Chain comparison Operators
The aggregation of comparison operators is another sometimes handy technique:
n = 10result = 1 < n < 20print (result) # True result = 1 > N <= 9print (result) # False
Tips. Using ternary operators for conditional assignment
The ternary operator is a shortcut to the If-else statement, which is the conditional operator:
[Expression is true return value] if [expression] else [expression is false return value]
Here are a few examples that you can use to make your code compact and concise. The following statement says "If Y is 9, give X a value of 10, or assign a value of 20". We can also extend this chain of operations if needed.
x = Ten if (y = = 9) Else 20
In the same way, we can do this with classes:
x = (ClassA if y = = 1 else classB) (param1, param2)
In the example above, ClassA and ClassB are two classes, and the constructors of one class are called.
Here is another example where multiple conditional expressions are linked to calculate the minimum value:
Def small (A, B, c): Return a If a <= B and a <= c else (b if B <= A and B <= c else c) 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 the ternary operator in the list deduction:
[m**2 if M > Else m**4 for M in range] #=> [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, 129 6, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
Tips # # #. Multi-line string
The basic way is to use a backslash from the C language:
MULTISTR = "SELECT * from Multi_rowwhere row_id < 5" Print (MULTISTR) # select * from Multi_row where row_id < 5
Another technique is to use three quotation marks:
Multistr = "" "Select * from Multi_rowwhere row_id < 5" "" Print (MULTISTR) #select * from Multi_row#where row_id < 5
The common problem with the above method is that there is a lack of proper indentation, and if we try to indent we will insert spaces into the string. 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 r OW_ID < 5 ORDER BY age
Tip # # #. To store list elements in a new variable
We can use lists to initialize multiple variables, and when parsing a list, the number of variables should not exceed the list of elements: "Translator Note: The number of elements and the length of the list should be strictly the same, or it will be an error"
Testlist = [1,2,3]x, y, z = testlist print (x, y, z) #-> 1 2 3
Tips. Print the file path of the ingest module
If you want to know the absolute path to the module referenced in your code, you can use the following tips:
Import threadingimport 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 ' >
Tips. "_" operator in 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 + 13>>> _3>>> Print _3
"_" is the output of the last executed expression.
Tips. Dictionary/Collection derivation
Similar to the list deduction we used, we can also use dictionary/set derivation, which is simple and effective, and here's an example:
Testdict = {I:I * I for I in Xrange (ten)}testset = {I * 2 for I in Xrange (Ten)} 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 in two statements, and when you run the above code in Python3, <xrange> changes to <range>.
Tip # #. Debug scripts
We can set breakpoints in the Python script with the help of the <pdb> module, here's an example:
Import Pdbpdb.set_trace ()
We can specify <pdb.set_trace () > anywhere in the script and set a breakpoint there, quite simply.
Tip # #. Open File Sharing
Python allows you to run an HTTP server to share files from the root path, and the following is the command to open the server:
# python 2python-m simplehttpserver# python 3python3-m http.server
The above command opens a server on the default port, 8000, and you can pass a custom port number to the command above with the last parameter.
Tips #11. Check for objects in Python
We can examine the 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 ']
Tips #12. Simplifying IF statements
We can validate multiple values using the following method:
If m in [1,3,5,7]:
Instead of:
If M==1 or m==3 or m==5 or m==7:
Alternatively, we can use ' {1,3,5,7} ' instead of ' [1,3,5,7] ' for the in operator, because the take element in set is an O (1) operation.
Tips #13. Run-time detection of Python version
Sometimes we may not want to run our program when a running Python is below a supported version. To achieve this goal, you can use the following code snippet, which also outputs the current Python version in a readable manner:
Import SYS #Detect the Python version currently in Use.if not HASATTR (sys, "hexversion") or sys.hexversion! = 50660080: Print ("Sorry, aren ' t running on Python 3.5n") print ("Please upgrade to 3.5.N") sys.exit (1) #Print Python Versio N in a readable format.print ("Current Python version:", sys.version)
Or you can use Sys.version_info >= (3, 5) to replace the sys.hexversion! = 50660080 in the code above, which is a reader's recommendation.
Results from running on Python 2.7:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on Linux
Sorry, aren ' t running on Python 3.5
Upgrade to 3.5.
Results from running on Python 3.5:
Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on Linux
Current Python version:3.5.2 (default, 22 2016, 21:11:05)
[GCC 5.3.0]
Tips #14. Combining multiple strings
If you want to stitch all the marks in the list, like the following example:
>>> test = [' I ', ' like ', ' Python ', ' automation ']
Now, let's create a new string from the list element given above:
>>> print '. Join (TEST)
Tips #15. Four ways to flip a string/list
# Flip the list itself
Testlist = [1, 3, 5]testlist.reverse () print (testlist) #-> [5, 3, 1]
# Flip and iterate the output in a loop
for element in reversed ([1,3,5]): print (Element) #1, 5#2-> 3#3-> 1
# One line of code flips the string
"Test Python" [::-1]
Output as "Nohtyp Tset"
# Flip a list with slices
[1, 3, 5] [::-1]
The above command will give the output [5,3,1].
Tips #16. Topsy enumeration
Using enumerations makes it easy to find (the current) index in a loop:
Testlist = [Ten, 30]for I, value in enumerate (testlist): Print (i, ': ', value) #1 0:10#2-> 1:20#3-> 2 : 30
Tips #17. Using enumerators in Python
We can use the following method to define the enumeration amount:
Class Shapes:circle, Square, Triangle, quadrangle = Range (4) print (shapes.circle) print (shapes.square) print (Shapes.tri Angle) print (shapes.quadrangle) #1, 0#2-> 1#3-> 2#4-> 3
Tips #18. Returning multiple values from a method
There are not too many programming languages to support this feature, but the method in Python does (CAN) return multiple values, see the example below to see how this works:
# function returning multiple Values.def x (): Return 1, 2, 3, 4 # Calling the above Function.a, B, c, d = x () print (A, b, C, D) #-> 1 2 3 4
Tips #19. Use the * operator (splat operator) to unpack function parameters
The * operator (Splat operator) provides an artistic method to unpack the parameter list, for clarity see the following example:
def test (x, Y, z): print (x, y, z) testdict = {' x ': 1, ' Y ': 2, ' z ': 3}testlist = [ten,] Test (*testdict) test (**test Dict) test (*testlist) #1 x y z#2-> 1 2 3#3-> 10 20 30
Tips #20. Use a dictionary to store selection actions
We can construct a dictionary to store expressions:
Stdcalc = {' Sum ': lambda x, y:x + y, ' subtract ': lambda x, y:x-y} print (stdcalc[' sum ') (9,3)) print (stdcalc[' subt Ract '] (9,3) #1, 12#2-> 6
Tips #21. 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) #-> 6Python 3.x.import Functoolsresult = (Lambda k:functools.reduce (int.__mul__, Range (1,k+1), 1)) (3) print (result) #-> 6
Tips #22. Find the most frequently occurring number in the list
Test = [1,2,3,4,2,2,3,1,4,4,4]print (max (set (test), Key=test.count)) #-> 4
Tips #23. Reset recursion Limit
Python limits recursion to 1000, and we can reset this value:
Import sys x=1001print (Sys.getrecursionlimit ()) sys.setrecursionlimit (x) print (Sys.getrecursionlimit ()) #1 1000 1001 #2
Please use the above techniques only when necessary.
Tips #24. Check memory usage of an object
In Python 2.7, a 32-bit integer takes 24 bytes and uses 28 bytes in Python 3.5. To determine memory usage, we can call the Getsizeof method:
In Python 2.7, import sysx=1print (sys.getsizeof (x)) #-> 24 in Python 3.5 import sysx=1print (sys.getsizeof (x)) #-> 28
Tips #25. Use __slots__ to reduce memory costs
Have you noticed that your Python app consumes a lot of resources, especially memory? One technique is to use the __SLOTS__ class variable to reduce memory costs to some extent.
Import sysclass filesystem (object): def __init__ (Self, files, folders, devices): self.files = files self.folders = folders self.devices = devicesprint (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, you can see from the results that there is a real savings in memory usage, but you should only use __slots__ when the memory overhead of a class is unnecessarily large. Use it only after profiling your app, otherwise you just make the code difficult to change without real benefits.
"The Translator notes: The result in my Win10 python2.7 is:
#In Python 2.7 win10#1-> 896#2-> 1016
So, this comparison is less convincing, the use of __slots__ is mainly used to limit the object's property information, in addition, when the object is generated a lot of costs may be smaller, see the official Python document:
The slots declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a Val UE for each variable. Space is saved because dict are not created for each instance. 】
Tips #26. Using lambda to mimic the output method
Import Syslprint=lambda *args:sys.stdout.write ("". Join (Map (Str,args))) lprint ("Python", "Tips", 1000,1001) #-> Python Tips 1000 1001
Tips #27. Build a dictionary from two related sequences
T1 = (1, 2, 3) t2 = (Ten, ()) print (Dict (Zip (t1,t2))) #-> {1:10, 2:20, 3:30}
Tips #28. A line of code searches for multiple prefixes of a string
Print ("http://www.google.com". StartsWith (("http://", "https://")) print ("http://www.google.co.uk". EndsWith (". Com ",". co.uk "))) #1-true#2-> True
Tips #29. Construct a list without using loops
Import Itertoolstest = [[-1,-2], [[+], [35]]print] (list (itertools.chain.from_iterable (test))) #-> [-1,-2, 30, 40, 25, 35]
Tips #30. 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): Return Xswitch._system_dict.get (x, None) xswitch._system_dict = {' Files ': Ten, ' Folders ': 5, ' devices ': 2} print (Xswitch (' Default ')) Print (Xswitch (' devices ')) #1 none#2-> 2
This article is from the "Baby God" blog, make sure to keep this source http://babyshen.blog.51cto.com/8405584/1916211
30 Useful tips for Python