Python common 30 programming skills, start by divine intervention

The position of the two digital direct exchange
Python provides an intuitive way to exchange assignments and (variable value) of one 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 assignment of the right to form a new tuple, and the left is immediately (not referenced) to unpack name tuple and .

After the assignment is completed, the new tuple becomes unreferenced state, and may be labeled as garbage collection, and ultimately it happened digital switching.

Link comparison operators
comparison operators sometimes polymerization is another technique used up very smoothly.

n = 10
result = 1 < n < 20
print(result)

# True

result = 1 > n <= 9
print(result)

# False

Ternary conditional assignment operator
ternary operator if-else statement is (i.e. conditional operator) shortcuts:

[on_true] if [expression] else [on_false]

Two examples examples show how you can use this technique to make your code more compact and more concise.

The following statement means "If y is 9, to assign 10 to x, otherwise assign 20 to x". If required, we can expand the operator link:

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

Similarly, we can also operate on class objects:

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

In the above example, the class classA with classB are two classes, a class constructor is called.

Multi-line strings using
this method is to use a backslash 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, will insert a space in the string.

Therefore, the final solution is the string into multiple lines, and 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 of new variables
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 it will error.

testList = [1,2,3]
x, y, z = testList

print(x, y, z)

#-> 1 2 3

Print out the module to import the file path
if you want to know the absolute path in the code to import the module, use the following tips will do this:

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'>

Using interactive "_" operator
fact, this is a very useful feature, but many of us did not notice.

In the Python console, whenever we test an expression or calls a function, the result will be assigned a temporary name, _ (an underscore).

>>> 2 + 1
3
>>> _
3
>>> print _
3

Here the "_" is the result of an expression of an execution.

Dictionary / collection derive
just as we use a list of expressions, we can also use a dictionary / collection derivation. Very simple to use, and very effective, for example:

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: In both statements, <:> only difference one. Further, if you want to use the above code Python3 operation, it should <xrange>replace <range>.

Debug scripts
we can use the <pdb>module to set breakpoints in a Python script, as follows:

import pdb
pdb.set_trace()

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

Set Up File Sharing
Python allows us to run HTTP server can be used for file sharing server root directory. Start the server command is as follows:

# Python 2:
python -m SimpleHTTPServer

# Python 3:
python3 -m http.server

The above command will start a server on port 8000 by default, you can also use a custom port, the port as the last element of the above commands can be passed.

In the examination subject Python
we can call dir () method checks objects in Python, the following 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 the if statement

We can verify that the plurality of values ​​by:

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

Instead of this:

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

For in operator, we can also use '{1,3,5,7}' instead of '[1,3,5,7]', as 'set' can be (1) acquired by each element O.

Detected at runtime version of Python
sometimes if the Python version of the currently running below the support, we might not want to execute the program. Then it can detect the version of Python script with the following code. You can print out the Python version currently used in a readable format.

import sys

#检测当前所用的Python版本
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)
 
#以可读格式打印出Python版本
print("Current Python version: ", sys.version)
另外,你可以将上面代码中的 sys.hexversion!= 50660080 替换为 sys.version_info >= (3, 5)。

Python 2.7 is running in output:

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.

In Python 3.5 running output:

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 all the token splicing list, then look at the following example to understand:

>>> test = ['I', 'Like', 'Python', 'automation']

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

>>> print ''.join(test)

4 ways flip string / list

#翻转列表本身
testList = [1, 3, 5]
testList.reverse()
print(testList)

#-> [5, 3, 1]

#在循环中迭代时翻转
for element in reversed([1,3,5]): print(element)

#1-> 5
#2-> 3
#3-> 1

#翻转一行代码中的字符串
"Test Python"[::-1]

We will get results "nohtyP tseT".

#用切片翻转一个列表
[1, 3, 5][::-1]

The above command will be output [5, 3, 1].

Enum
enum can easily find the index in the cycle:

testlist = [10, 20, 30]
for i, value in enumerate(testlist):
 print(i, ': ', value)

#1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30
在 Python 中使用枚举量
我们可以用如下方法来创建枚举定义:

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 a function

Support this feature of programming languages ​​is not much, however, Python functions can return multiple values.

Refer to the following example to see how you do it:

# 返回多个值的函数
def x():
 return 1, 2, 3, 4

# 调用上面的函数
a, b, c, d = x()

print(a, b, c, d)

#-> 1 2 3 4

* Operator using the decompression function parameters

Operators of art provides a way to decompress the parameter list, with reference to 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 the expression

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

Calculate any line of code numbers factorial

# 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 a list of the most frequent values

test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count))

#-> 4
重置递归限制
Python 将递归限制到 1000,我们可以重置这个值:

import sys

x=1001
print(sys.getrecursionlimit())

sys.setrecursionlimit(x)
print(sys.getrecursionlimit())

#1-> 1000
#2-> 1001

Tip: Use this technique only when necessary.

A memory check objects used
in Python 2.7, a 32-bit integer value occupies 24 bytes, while in Python 3.5 occupies 28 bytes. We can call methods to verify memory use.

In Python 2.7 are:

import sys
x=1
print(sys.getsizeof(x))

#-> 24

In Python 3.5 are:

import sys
x=1
print(sys.getsizeof(x))

#-> 28

Use _slots_ reduce memory consumption

I do not know if you noticed your Python programs will take up a lot of resources, especially memory? Here to share with you a technique, using < slots memory consumption> class variables to reduce 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

Obviously, you can see from the dismissal save some memory. However, should no longer use this method when a class of large memory footprint is not necessary. Application performance analysis before using it, or in addition to make the code difficult to change outside does not do any good.

To simulate the output method using lambda

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}

Line of code with the prefix and suffix search string

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

#1-> True
#2-> True

Do not use any loop construct a list

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 contains a list of embedded elements, or tuples, then the following this method, but also has limitations, for it uses the 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]

Achieve a real switch-case statement in Python

Here is an example of a dictionary just mimic the switch-case structure:

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

Python want to list these above tips and suggestions can help you complete Python developers quickly and efficiently, they can be used in the project.

As a someone who has, I have to tell you to ask the older cattle is really important, so that you can take a lot less detours, do not be afraid shame, no face, the face value of some money? Learn a real skill is most important. No skill called really no face. python technology sharing , so that your future is no longer confused.

Recommended reading: zero-based learning Python, sooner understand this, the sooner you find a good job!

Guess you like

Origin blog.csdn.net/weichen090909/article/details/90647683