Python programming to enhance the efficiency of several methods

Foreword

We know this language Python running speed has been lost to many other languages (such as C, C ++, Java, Golang ....). But from the perspective of a developer's perspective Python is my favorite language, in large part because its syntax is simple (in fact, I'm lazy), there are many very sao operation, can greatly improve the efficiency of our knock code. we usually call this operation for the sao pythonic.

Python's sao operating a lot, here are a few first, after more slowly.

1. exchange of two variables

Traditional writing:

temp = a
a = b
b = temp

pythonic:

a, b = b, a

2. Enumeration enument

Imagine a scenario, there is a list ["老胡", "老王", "老李", "老赵"], now requires you to create a dictionary, a dictionary which each key is an element of the list, value for the corresponding element of the index, how to do? This is not the best use of enumeration scene, here is just one example, to tell you the enumeration is actually very good use.

Traditional writing:

alist = ["老胡", "老王", "老李", "老赵"]

aDict = {}

for i in range(len(alist)):
    aDict[alist[i]] = i

pythonic:

alist = ["老胡", "老王", "老李", "老赵"]

aDict = {}

for index, item in enumerate(alist):
    aDict[item] = index

3. Derivation of formula

Python is divided into three derivation 列表推导式, 字典推导式, 集合推导式, due to the collection and derivation list comprehensions bore a striking resemblance here is not too much in the presentation.

List comprehensions

Imagine a scene, we ask you to put all the even-numbered 1 to 100 in the list evenList

Traditional writing:

evenList = []

for i in range(0, 101):
   if i % 2 == 0:
       evenList.append(i)

pythonic:

evenList = [i for i in range(0,101) if i % 2 == 0]

Only one line of code is not so cool it.

It gives a list of specifications derived formula:

variable = [out_exp for out_exp in input_list if 某个条件成立]

Dictionary derivations

Imagine a scenario where you have all the requirements of a dictionary key and value exchange position

Traditional writing:

ADict = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

BDict = {}

for key, value in ADict.items():
    BDict[value] = key

pythonic:

ADict = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

BDict = {value: key for key, value in ADict.items()}

Familiar with derivations can make your code becomes very short!

4.lambda expression

This is undoubtedly a very important grammatical, but many newcomers do not like to use ...

The so-called lambda expression is an anonymous function, why should we use anonymous function? There are times when we want to use a function but the entire program only need to use this time, this time using a lambda expression is undoubtedly the most convenient

Imagine a scenario, there is a list stored inside the tuple pair, and now the second element Yaoan tuples of the list is sorted

Traditional method:

aList = [(2, 3), (1, 2), (4, 5), (7, 4)]


def sortKey(x):
    return x[1]


aList.sort(key=sortKey)     # 注意不要写成aList = aList.sort(key=sortKey),它没有返回值

print(aList)

out:

[(1, 2), (2, 3), (7, 4), (4, 5)]

pythonic:

aList = [(2, 3), (1, 2), (4, 5), (7, 4)]

aList.sort(key=lambda x: x[1])

out:

[(1, 2), (2, 3), (7, 4), (4, 5)]

Given specifications:

lambda 参数:操作(参数)

Note that the latter 操作(参数)is to be returned

for example:

add = lambda x, y: x + y
# 等价于下面的函数
def add(x, y):
    return x + y

5. decorator

Python decorator is very, very important knowledge, application examples only here, then I will be out a detailed explanation decorator

Imagine a scenario, the company has a lot of department (function) in operation at the same time, under the now ask you to run the code without changing the conditions for each department added a new feature

Source:

def partA():
    print("----do A job----")

def partB():
    print("----do B job----")

def partC():
    print("----do C job----")

if __name__ == '__main__':
    partA()
    partB()
    partC()

out:

----do A job----
----do B job----
----do C job----

Traditional method:

def partA():
    print("----do A job----")
    print("****do extra job****")

def partB():
    print("----do B job----")
    print("****do extra job****")

def partC():
    print("----do C job----")
    print("****do extra job****")

if __name__ == '__main__':
    partA()
    partB()
    partC()

out:

----do A job----
****do extra job****
----do B job----
****do extra job****
----do C job----
****do extra job****

pythonic:

def doExtraJob(func):
    def wrap():
        func()
        print("****do extra job****")
    return wrap

@doExtraJob
def partA():
    print("----do A job----")

@doExtraJob
def partB():
    print("----do B job----")

@doExtraJob
def partC():
    print("----do C job----")

if __name__ == '__main__':
    partA()
    partB()
    partC()

out:

----do A job----
****do extra job****
----do B job----
****do extra job****
----do C job----
****do extra job****

Adding new functions in comparison of the two methods, the decorator effect is that it allows a function do not change the internal code of the situation.

6. magical else statements

Most people only know the else statement and used with the if statement, but you know what else statements, and may also forstatements, whilestatements tryused with statement

Imagine a scene when you were in the loop on an internal list of unknown data (either foror while), you set up a face to break even number of statements, if the array does not contain an even number of outputs 奇数列表words.

Traditional method:

aList = [1, 3, 5, 7, 9]

flag = True
for i in aList:
    if i % 2 == 0:
        flag = False
        break

if flag:
    print("奇数列表")

pythonic:

aList = [1, 3, 5, 7, 9]

for i in aList:
    if i % 2 == 0:
        flag = False
        break
else:
    print("奇数列表")

Note that the loop ( foror while) the else statement (that is, when not due to a break statement exits) triggered when the loop exits normally

To the try,elsestatement, else statement will be triggered when an exception is not, perhaps you have questions, there is no abnormality in the statement is not directly try to solve it, but try statement will be captured in the operation, sometimes we do not think so.

Look at an example:

try:
    assert True
except:
    print("出错了")
else:
    print("没有错")

out:

没有错

assertAs for the assertion that the latter statement is false is reported to be abnormal, and this trystatement is sometimes used together will be very convenient.

7.map function

map function will be a function mapped to a list of all the elements up. This is simply a perfect fit and lambda expressions.

Imagine a scenario, where a list of ten numbers 1-10, hereby demand will square every number in this list is stored in another list, this is not difficult

Traditional method:

aList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

bList = []
for i in aList:
    bList.append(i**2)

pythonic:

aList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

bList = list(map(lambda x:x**2, aList))

Be careful not map the function returns a list map对象, you need to type conversion

8.filter function

Right from the name of the function can be seen filterperformance function is to filter, filteryou can filter element and returns a list of all meet the requirements of the elemental composition filter对象, and mapsimilar attention to the type of conversion.

Imagine a scenario, there is a list, which kept some unknown figures, now ask you to put all even picked out,

Traditional method:

aList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

bList = []
for each in aList:
    if each % 2 == 0:
        bList.append(each)

pythonic:

aList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

bList = list(filter(lambda x: not x % 2, aList))

Used here notbecause the even number 2 is more than 0 (Python 0 is False), in order to make an even number when returns True, except for a not

9.reduce function

Note: the front and two different functions, the reduce function is put functoolsthis module, use need to import.

reduceFunction will be a list of all the elements have carried out operations with a function that requires this function must have two parameters.

Imagine a scenario requires seeking a list of numbers in the average of all the numbers.

Traditional method:

aList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

sum = 0
for i in aList:
    sum += i

ave = sum / len(aList)

pythonic:

from functools import reduce

aList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

ave = reduce(lambda x, y: x + y, aList) / len(aList)

map, filter, reduceFunctions, and lambdawith the use of is the essence. There are three functions do not confuse functions

Function name Features return value
map All the elements of a simple function to map a list of up to map objects
filter Filter element and returns a list of all the elements to meet the requirements of filter objects filter objects
reduce A list of all the elements have carried out operations with a function Calculation results

10. summary

Python sao operation of many, the hope brought by several usage so useful for people who are new to easy to forget, I hope you can be more hands-on code that knocked enhance memory, to see you before writing code it possible to use these altered sao operation, make your code more streamlined look.

Guess you like

Origin www.cnblogs.com/kainhuck/p/10987747.html