Advanced features ython you Know? To compare the look

Python and more easy to use Needless to say, look at the language they used to know. But Python to hide the advanced features you get it? In this paper, the author enumerates five kinds of Python slightly advanced features as well as methods for their use, come check it out now!
Python is a beautiful language, it is easy to use but very powerful. But you really use all the features of Python do?

Advanced features of any programming language are usually through a lot of experience only to find. For example, you are writing a complex project, and find answers to a question on stackoverflow. Then you suddenly found a very elegant solution, which uses the Python function you never know!

This method of learning is so interesting: by exploring, occasionally find anything.

Below are five kinds of advanced features Python, as well as their usage.

Lambda function

Lambda function is a relatively small anonymous functions - Anonymous means that it does not actually function name.

Python functions typically use def a_function_name () to define the style, but for lambda functions, we did not name it. This is because the function lambda function is to perform some simple expressions or operations, without completely defined functions.

lambda functions can be used any number of arguments, but only one expression.

x = lambda a, b : a * b
print(x(5, 6)) # prints '30'

x = lambda a : a*3 + 3
print(x(3)) # prints '12'

Look how simple it! We performed some simple mathematical operations, without having to define the entire function. This is one of the many features of Python, these features make it a clean, simple programming language.

Map function

Map () function is a built Python, a function which can be applied to various elements in a data structure, such as lists or dictionaries. For this calculation, it is a very clean and readable implementation.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:××× 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def square_it_func(a):
    return a * a

x = map(square_it_func, [1, 4, 7])
print(x) # prints '[1, 16, 49]'

def multiplier_func(a, b):
    return a * b

x = map(multiplier_func, [1, 4, 7], [2, 5, 8])

print (x) # prints '[2, 20, 56]' See above example! We can be applied to a single function or multiple lists. In fact, you can use any Python function as an input map function, sequence elements as long as it is operating and you are compatible.

Filter function

filter with built-in function is very similar to the map function, it will also function to the sequence structure (lists, tuples, dictionaries). The key difference is that the filter () will only return the application function returns True elements.

For more details, see the following example:

# Our numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

# Function that filters out all numbers which are odd
def filter_odd_numbers(num):

    if num % 2 == 0:
        return True
    else:
        return False

filtered_numbers = filter(filter_odd_numbers, numbers)

print(filtered_numbers)
# filtered_numbers = [2, 4, 6, 8, 10, 12, 14]

Not only do we evaluated the True or False for each list element, filter () function also ensures that only the return match for the True elements. Very easy to check the expression and processing returns to build a list of these two steps.

Itertools module

The tool module is the Python Itertools processing iteration is set. Iterator is a type of data may be in the loop for (including a list of tuples, and dictionaries) used.

Use function Itertools module allows you to perform many iterator operations that usually require multiple lines of a list of functions and complex to understand. About Itertools magic, consider the following example:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:××× 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from itertools import *

# Easy joining of two lists into a list of tuples
for i in izip([1, 2, 3], ['a', 'b', 'c']):
    print i
# ('a', 1)
# ('b', 2)
# ('c', 3)

# The count() function returns an interator that 
# produces consecutive integers, forever. This 
# one is great for adding indices next to your list 
# elements for readability and convenience
for i in izip(count(1), ['Bob', 'Emily', 'Joe']):
    print i
# (1, 'Bob')
# (2, 'Emily')
# (3, 'Joe')    

# The dropwhile() function returns an iterator that returns 
# all the elements of the input which come after a certain 
# condition becomes false for the first time. 
def check_for_drop(x):
    print 'Checking: ', x
    return (x > 5)

for i in dropwhile(should_drop, [2, 4, 6, 8, 10, 12]):
    print 'Result: ', i

# Checking: 2
# Checking: 4
# Result: 6
# Result: 8
# Result: 10
# Result: 12

# The groupby() function is great for retrieving bunches
# of iterator elements which are the same or have similar 
# properties

a = sorted([1, 2, 1, 3, 2, 1, 2, 3, 4, 5])
for key, value in groupby(a):
    print(key, value), end=' ')

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

Function Generator

Generator function is a function similar to iterator that it can also be used in the for loop statement. This greatly simplifies your code, and compared to a simple for loop, it saves a lot of memory.

For example, we want all the numbers 1-1000 are added, the first part of this block of code to show you how to use a for loop to perform this calculation.

If the list is small, such as 1000 rows, the required computer memory okay. But if the giant long list, such as one billion floating-point numbers, this problem will appear. Use this for loop, a large number in the memory list, but not everyone has unlimited RAM to store so many things. Python in the range () function is so dry, it builds a list in memory.

Code shows the use of a second portion of the digital Python generator function that sums. generator function to create an element, and only if necessary in memory that stores one at a time. This means that if you want to create one billion floating-point numbers, you can put them one at a time in memory! The Python 2.x xrange () function is to use a generator to build a list.

These examples show: If you want to generate a list of a wide range, then you need to use the generator function. If you have limited memory, such as the use of mobile computing devices or edge, using this method is particularly important.

That is, if you want to list a number of iterations, and it is small enough to put in the memory, it is best to use a for loop or Python 2.x function of range. Because the generator function and xrange function will be generated every time you visit their new list of values, and Python 2.x range function is static list, and integer been placed in memory for quick access.

# (1) Using a for loopv
numbers = list()

for i in range(1000):
    numbers.append(i+1)

total = sum(numbers)

# (2) Using a generator
 def generate_numbers(n):
     num, numbers = 1, []
     while num < n:
           numbers.append(num)
     num += 1
     return numbers
 total = sum(generate_numbers(1000))

 # (3) range() vs xrange()
 total = sum(range(1000 + 1))
 total = sum(xrange(1000 + 1))

Guess you like

Origin blog.51cto.com/14246112/2443427