30 small python practical tips

1. The two digital switching situ

Python is provided a method in a visual line of code assigned to the exchange (variable value), see the following example:

In [1]: x,y = 10 ,20 

In [2]: print(x,y)
10 20

In [3]: x, y = y, x 

In [4]: print(x,y)
20 10

The right to form a new assignment tuple parsed immediately left (the unpack) that (unreferenced) tuple to the variable <x> and <y>.

Once the assignment is completed, the new tuple into a reference state and is not marked as garbage collection may be, eventually completed the exchange of variables.

2. Comparison Operators chain

Comparison operator sometimes convenient polymerization is another technique:

In [5]: n = 10 

In [6]: result = 1 < n < 20 

In [7]: result 
Out[7]: True

In [8]: result = 1 > n <= 9 

In [9]: result 
Out[9]: False

3. ternary operator to assign conditions

Ternary operator if-else statement is a shortcut that is conditional operator:

[表达式为真的返回值] if [表达式] else [表达式为假的返回值]

Here you may be used to give a few simple examples of compact code. The following statement is saying "if y is 9 to 10 x assignment, or assignment is 20." If necessary we can also extend this chain of operations.

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

Similarly, we can do this kind of operation on the class:

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

In the example above two classes classA and the classB is, a class constructor which will be called.

The following is a plurality of conditional expression linked to another example of the calculation of the minimum value:

In [10]: def small(a,b,c):
    ...:     return a if a<=b and a<=c else ( b if b<=a and b<=c else c) 
    ...: 

In [11]: small(1,0,1)
Out[11]: 0

In [12]: small(1,2,3)
Out[12]: 1

We can even use the ternary operator in the derivation list:


In [14]: [ m**2 if m > 10 else m**4 for m in range(20) ] 
Out[14]: 
[0,1,16,81,256,625,1296,2401,4096,6561,10000,121,144,169,196,225,256,289,324,61]

4. The multi-line character string

The basic approach is to use C language derived from the backslash:

In [20]: multistr = " select * from multi_row \
    ...: where row_id < 5"

In [21]: multistr
Out[21]: ' select * from multi_row where row_id < 5'

Another trick is to use triple quotes

In [23]: multistr ="""select * from multi_row 
    ...: where row_id < 5"""

In [24]: multistr
Out[24]: 'select * from multi_row \nwhere row_id < 5'

The above method common problem is the lack of proper indentation, if we try indentation will insert a space in the string. So the final solution is to break the string into multiple lines and the entire string enclosed in brackets:

In [25]: multistr = ("select * from multi_row "
    ...: "where row_id < 5 " 
    ...: "order by age")  

In [26]: multistr
Out[26]: 'select * from multi_row where row_id < 5 order by age'

The list elements stored in the new variables

We can use the list to initialize multiple variables, when parsing the list, the number of variables should not exceed the number of elements in the list: [Translator's Note: The number of elements and the length of the list should be exactly the same, or will be error]

In [27]: testlist = [1,2,3] 

In [28]: x,y,z = testlist 

In [29]: print(x,y,z) 
1 2 3

6. The print module file path introduced

If you want to know the absolute path to reference the code module, you can use the following tips:

In [30]: import threading 

In [31]: import socket 

In [32]: print(threading)
<module 'threading' from '/usr/local/lib/python3.5/threading.py'>

In [33]: print(socket) 
<module 'socket' from '/usr/local/lib/python3.5/socket.py'>

"_" Operator in the interactive environment 7.

This is a most of us do not know of useful features in Python console, whenever we test an expression or call a method, the result will be assigned to a temporary variable: _ (underscore).

In [34]: 2 + 3 
Out[34]: 5

In [35]: _
Out[35]: 5

In [36]: print(_) 
5

"_" Is the expression of an execution output.

8. dictionary / collection derivations

We use a list similar derivation, we can use a dictionary / collection derived, which is simple and effective to use, the following is an example:

In [37]: testDict = {i : i*i for i in range(5)} 

In [38]: testSet = { i*2 for i in range(5)} 

In [39]: testDict
Out[39]: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

In [40]: testSet
Out[40]: {0, 2, 4, 6, 8}

Note: only two statements a <:> is different from the other, run code Python3 above, the <xrange> to <range>.

9. debug scripts

We can set breakpoints in a Python script with the help of <pdb> module, the following is an example:

import pdb
pdb.set_trace()

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

10. Turn on file sharing

Python allows HTTP server running a path from the root to share files, the following command server is open: (python3 Environment)

python3 -m http.server

The above command will open the default port 8000 is a server, the port number you can be a custom passed to the command above by way of the last parameter.

Paste_Image.png

11. The inspection object in Python

We can inspect objects in Python by calling dir () method, the following is a simple example:

In [41]: test = [1,3,5,7]

In [42]: print(dir(test)) 
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Listed property methods of the object.

12. simplified if statement

We can use the following way to verify multiple values:

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

Instead of

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

Alternatively, we can for the operator in use '{1,3,5,7}' instead of '[1,3,5,7]', because the set of elements having a O (1) operations.

13. runtime version detecting Python

When running below the support Python versions, sometimes we may not want to run our program. To achieve this, you can use the following code fragment, it outputs the current in a manner readable version of Python:

import sys
 
#Detect the Python version currently in use.
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
    print("Sorry, you aren't running on Python 3.5n")
    print("Please upgrade to 3.5.n")
    sys.exit(1)
 
#Print Python version in a readable format.
print("Current Python version: ", sys.version)

Or you can use sys.version_info> = (3, 5) to replace the above code sys.hexversion! = 50660080, it is recommended that a reader.

python3 operating results:

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]

14. A combination of a plurality of strings

If you want to mark all the stitching in the list, such as the following example:

In [44]: test = ['I', 'Like', 'Python', 'automation']

In [45]: ''.join(test)
Out[45]: 'ILikePythonautomation'

15. The string of four kinds of flip / list mode

Flip the list itself

In [49]: testList = [1, 3, 5] 

In [50]: testList.reverse() 

In [51]: testList
Out[51]: [5, 3, 1]

Flip and iteratively in a loop output

In [52]: for element in reversed([1,3,5]):
    ...:     print(element) 
    ...:     
5
3
1

Flip line of code string

In [53]: "Test Python"[::-1]
Out[53]: 'nohtyP tseT'

Use slice flip List

[1, 3, 5][::-1]

16. Fun Enumeration

Use enumeration can easily find the (current) index in the cycle:

In [54]: testList= [10,20,30] 

In [55]: for i,value in enumerate(testList):
    ...:     print(i,':',value)
    ...:     
0 : 10
1 : 20
2 : 30

17. Use enum in python

We can use the following way to define enum:

In [56]: class Shapes:
    ...:     Circle,Square,Triangle,Quadrangle = range(4) 
    ...:     

In [57]: Shapes.Circle
Out[57]: 0

In [58]: Shapes.Square
Out[58]: 1

In [59]: Shapes.Triangle
Out[59]: 2

In [60]: Shapes.Quadrangle
Out[60]: 3

18. A plurality of values ​​returned from the method

And there is not much programming language that supports this feature, but the method in Python do (can) return multiple values, see the following example to see how this works:

In [61]: def x():
    ...:     return 1,2,3,4 
    ...: 

In [62]: a,b,c,d = x()

In [63]: print(a,b,c,d) 
1 2 3 4

20. The use a dictionary to store a selection operation

We can construct a dictionary to store the expression:

In [70]: stdacl = { 
    ...: 'sum':lambda x,y : x + y,
    ...: 'subtract':lambda x,y : x - y 
    ...: } 


In [73]: stdacl['sum'](9,3) 
Out[73]: 12

In [74]: stdacl['subtract'](9,3) 
Out[74]: 6

21. The line of code calculation of any factorial

python3 environment:

In [75]: import functools

In [76]: result = ( lambda k : functools.reduce(int.__mul__,range(1,k+1),1))(3) 

In [77]: result
Out[77]: 6

22. A number of the most frequently found appears in the list


In [82]: test = [1,2,3,4,2,2,3,1,4,4,4] 

In [83]: print(max(set(test),key=test.count)) 
4

23. Reset recursion limit

Python recursion limit to the number of 1000, we can reset this value:

import sys
 
x=1001
print(sys.getrecursionlimit())
 
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
 
#1-> 1000
#2-> 100

Modify cautious

24. Check memory usage of an object

In Python 2.7 in a 32-bit integer occupies 24 bytes by 28 bytes in Python 3.5. To determine memory usage, we can call getsizeof method:
python2.7:

import sys
x=1
print(sys.getsizeof(x))
 
#-> 24

python3:

In [86]: import sys 

In [87]: x = 1

In [88]: sys.getsizeof(x) 
Out[88]: 28

25. The use of slots to reduce memory costs

Have you noticed that your Python applications take up a lot of resources, especially memory? One trick is to use the slots class variables to reduce memory costs to some extent.

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, as you can see from the results really have to save on memory usage, but you should only be used when a class of memory overhead is unnecessarily large slots . Only use it only after the application performance analysis, or in words, you just make the code difficult to change and there is no real benefit.

26. A method of using the output to simulate lambda

In [89]: import sys 

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

In [91]: lprint("python","tips",1000,1001) 
Out[91]: pythontips1000100118

27. build a dictionary from two related sequences

In [92]: t1 = (1,2,3) 

In [93]: t2 =(10,20,30) 

In [94]: dict(zip(t1,t2)) 
Out[94]: {1: 10, 2: 20, 3: 30}

28. The plurality of line of code search string prefix and suffix

In [95]: print("http://www.google.com".startswith(("http://", "https://")))
True

In [96]: print("http://www.google.co.uk".endswith((".com", ".co.uk")))
True

29. The list does not use a loop construct

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

In [102]: import itertools

In [103]: print(list(itertools.chain.from_iterable(test)))
[-1, -2, 30, 40, 25, 35]

30. achieve a real switch-case statement in Python

The following code uses a dictionary configured to emulate a switch-case.

In [104]: def xswitch(x):
     ...:     return xswitch._system_dict.get(x, None) 
     ...: 

In [105]: xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2}

In [106]: print(xswitch('default'))
None

In [107]: print(xswitch('devices'))
2



Author: pirates of Luffy
link: https: //www.jianshu.com/p/cdceff697af8
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.

Guess you like

Origin blog.csdn.net/java276582434/article/details/92398223