30 must-know python tricks

Directly exchange the positions of 2 numbers

Python provides an intuitive way to assign and exchange (variable values) in a single 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, the right side of the assignment forms a new tuple, while the left side immediately unpacks the (unreferenced) tuple into the names and .

After the assignment is completed, the new tuple becomes unreferenced and marked as available for garbage collection, and eventually a digital exchange occurs.

chain comparison operator

Aggregation of comparison operators is another technique that sometimes comes in handy.

n = 10

result = 1 < n < 20

print(result)

True

result = 1 > n <= 9

print(result)

False

Conditional assignment using ternary operator

The ternary operator is a shortcut operation for the if-else statement (that is, the conditional operator):

[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 statement means "if y is 9, assign 10 to x, otherwise assign 20 to x." We can extend this operator chaining if needed:

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

Similarly, we can also do this for class objects:

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 will be called.

Use multiline strings

This method uses backslashes from the C language:

multiStr = "select * from multi_row \

where row_id < 5"

print(multiStr)

select * from multi_row where row_id < 5

Another trick is to use triple 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 proper indentation. If we want to indent, spaces will be inserted into the string. For newbies who want to learn the basics of Python, Python crawlers, web development, big data, data analysis, artificial intelligence and other technologies more easily, here we will give you systematic teaching resources, contact me Wei X: 762459510 [python tutorial/tool/method /Question]

So the final solution is to split the string into multiple lines and wrap 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 an error 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 an imported module in your code, just use this trick:

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 feature, but many of us don't notice 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

The "_" here is the result of the last executed expression.

Dictionary/set comprehension

Just like we use list expressions, we can also use dictionary/set comprehensions. 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 these two statements, <:>. In addition, if you want to run the above code with Python3, you need to replace it with.

debug script

We can set breakpoints in Python scripts with the help of modules as follows:

import pdb

pdb.set_trace()

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

Set up file sharing

Python allows us to run an HTTP server, which can be used to share files in the root directory of the server. 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 a custom port and pass the port as the last element to the above command.

Checking objects in Python

We can inspect 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’]

Simplify if statement

We can validate multiple values ​​as follows:

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

Instead of this:

if m1 or m3 or m5 or m7:

For the in operator, we can also use '{1,3,5,7}' instead of '[1,3,5,7]', because 'set' can obtain each element in O(1).

Detect Python version at runtime

Sometimes we may not want to execute the program if the currently running Python version is lower than the supported version. Then you can use the following code script to detect the Python version. It can also print out the currently used Python version in a human-readable format.

import sys

#Detect the currently used Python version

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 a readable format

print("Current Python version: ", sys.version)

In addition, you can replace sys.hexversion!= 50660080 in the above code with sys.version_info >= (3, 5).

The output when running in Python 2.7 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.

The output when running in Python 3.5 is:

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]

Combine multiple strings

If you want to splice all tokens in the list, then look at the following example:

test = [‘I’, ‘Like’, ‘Python’, ‘automation’]

Now we create a string from the elements of the list above:

print ‘’.join(test)

4 ways to flip a string/list

#flip the list itself

testList = [1, 3, 5]

testList.reverse()

print(testList)

#-> [5, 3, 1]

#Flip while iterating through the loop

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

#1-> 5

#2-> 3

#3-> 1

#Flip the string in a line of code

“Test Python”[::-1]

We will get the result "nohtyP tseT".

#Flip a list using slices

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

The above command will get the output result [5, 3, 1].

Use enumerations

It's easy to find the index in a loop using an enum:

testlist = [10, 20, 30]

for i, value in enumerate(testlist):

print(i, ': ', value)

#1-> 0 : 10

#2-> 1 : 20

#3-> 2 : 30

Using enumerations in Python

We can create an enumeration definition using the following method:

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

Return multiple values ​​from function

Not many programming languages ​​support this functionality, however, functions in Python can return multiple values.

You can refer to the following example to see how it is done:

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

Use the * operator to unpack function parameters

The * operator provides an artistic way to decompress the parameter list, 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 a dictionary to store expressions

stdcalc = {

‘sum’: lambda x, y: x + y,

‘subtract’: lambda x, y: x - y

}

print(stdcalc’sum’)

print(stdcalc’subtract’)

#1-> 12

#2-> 6

One line of code to calculate 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 a list

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

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

#-> 4

Reset recursion limit

Python limits 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 only when necessary.

Check the memory usage of an object

In Python 2.7, a 32-bit integer value takes up 24 bytes, and in Python 3.5 it takes up 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

Have you ever noticed that your Python program takes up a lot of resources, especially memory? Here is a trick to share with you, use <slots> class variables to reduce the memory consumption of the program.

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

It's obvious that some memory is saved from the dismissal. But this method should be used only when the memory footprint of a class is unnecessarily large. Performance analysis of the application before using it will do no good except make the code difficult to change.

Use lambdas to mimic output methods

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 the prefix and suffix of a string 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 the input list has embedded lists or tuples as elements, then use the following method, 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 is a code example that uses a dictionary to mimic a switch-case construct:

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

Conclusion

I hope the Python tips and suggestions listed above can help you complete Python development quickly and efficiently.

Guess you like

Origin blog.csdn.net/q762459510/article/details/127792000