Derivation of python

Source: Internet
Author: User

Derivation of python
Today, when looking at the company's batch deployment code (using fabric), I found a very interesting decorator, which uses the python derivation, especially to record it. The Code is as follows:

def host_restrict(tags=[], names=[]):    def decorator(f):        @functools.wraps(f)        def decorated(*args, **kwargs):            host_info = hosts.get(env.host)            if not host_info:                return f(*args, **kwargs)            if tags and host_info[0] not in tags:                raise StandardError('Tag %s not in %s' % (host_info[0], tags))            if names and not set(names).intersection(                    set([s for s in host_info[1].split(' ') if s.strip()])):                raise StandardError(                    'Name %s not in %s' % (host_info[1], names))            return f(*args, **kwargs)        return decorated    return decorator

 

Note: This decorator is mainly used to determine whether the user-entered tag and names meet the requirements. For example: # The host_info format is host_info = ['api ', 'nginx'] @ host_restrict (['api '], ['nginx']) def init ():... okay, don't pay attention to the details. There is a line of code that attracts my attention. set ([s for s in host_info [1]. split ('') if s. strip ()]) is a list derivation of python ,. The derivation is a powerful and popular feature in python. It has the advantages of concise language and fast speed. Derivation includes list derivation dictionary Derivation Set derivation nested list derivation NOTE: dictionary and set derivation were recently added to Python (Python 2.7 and Python 3.1 and later versions ). the following is a brief introduction: [LIST derivation] list derivation can create a new list in a very concise manner: only a concise expression can be used to convert and deform the elements. The basic format is as follows: [expr for value in collectionif condition] the filtering condition is optional. Depending on the actual application, only the expression is left, which is equivalent to the following for loop: result = [] forvalue in collection: ifcondition: result. append (expression) sample code :#! /Usr/bin/env python #-*-coding: UTF-8-*-# Example 1: filter out the list of strings whose length is less than 3, and convert the rest into uppercase letters names = ['bob', 'Tom ', 'Alice', 'Jerry ', 'wendy', 'Smith '] print [name. upper () for name in names if len (name)> 3] # Example 2: print the number of partitions that can be divisible by 3. print [x * x for x in range (10) if x % 3 = 0] Output: ['Alice ', 'Jerry', 'wendy ', 'Smith'] [0, 9, 36, 81] [dictionary derivation] The dictionary and set derivation are the continuation of this idea. The syntax is similar, but only the set and dictionary are generated. The basic format is as follows: {key_expr: value_expr for value in collection if condition} sample code :#! /Usr/bin/env python #-*-coding: UTF-8-*-# Example 1: Use dictionary derivation-create a dictionary strings = ['import' with a string and its length ', 'Is ', 'with', 'if', 'file', 'exception'] print {key: len (key) for val, key in enumerate (strings)} output: {'exception': 9, 'is: 2, 'file': 4, 'import': 6, 'with': 4, 'if ': 2} [set derivation] The set derivation is very similar to the list derivation. The only difference is that {} is used instead of []. The basic format is as follows: {expr for value incollection if condition} sample code :#! /Usr/bin/env python #-*-coding: UTF-8-*-# Example 1: Use a set to derive the strings = ['A', 'is ', 'with', 'if', 'file', 'exception'] print {len (s) for s in strings} output: set ([1, 2, 4, 9]) [nested list derivation] A nested list refers to a list of nested lists, such as: L = [[, 3], [, 6, 9] sample code: # Example 1: list comprehension replace nested loop print [[x, y] for x in range (3) for y in range (6)] # equivalent to z = [] for x in range (3): for y in range (6): z. append ([x, y]) print z # Example 2: A nested list composed of a list of men and women. The name contains two or more letters e, component list # implemented using a for Loop:
tmp = []names = [    ['Tom','Billy','Jefferson','Andrew','Wesley','Steven','Joe'],    ['Alice','Jill','Ana','Wendy','Jennifer','Sherry','Eva']]for lst in names:    for name in lst:        if name.count('e') >= 2:            tmp.append(name)print tmp

 

# Implement with nested list: print [name for lst in names for name in lst if name. count ('E')> = 2] Output: ['jefferson ', 'westsley', 'steven ', 'jennifer'] ['jefferson ', 'westsley ', 'steven ', 'jennifer']

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.