An introduction to the derivation in Python

Source: Internet
Author: User

The derivation is a very powerful and popular feature in Python, with the advantages of simple language and fast speed. The derivation formula includes:

    1. List-derived
    2. Dictionary derivation type
    3. Set Deduction formula
    4. Nested-List derivation

Note: dictionaries and set derivations are only recently added to Python (Python 2.7 and Python version 3.1 or later). The following is a brief introduction:

" List-derived "

List derivation can be very concise to construct a new list: The resulting element can be transformed with a simple expression

Its basic format is as follows:

[Expr for value in collection ifcondition]

Filter conditions are optional, depending on the actual application, leaving only the expression, equivalent to the following for loop:

result = []for value in collection:    if Condition:        result.append (expression)
Example 1: Filter out a list of strings that are less than 3 in length and convert the rest to uppercase letters
>>> names = [' Bob ', ' Tom ', ' Alice ', ' Jerry ', ' Wendy ', ' Smith ']>>> [Name.upper () for name in names if Len ( Name) >3][' ALICE ', ' JERRY ', ' WENDY ', ' SMITH ']
【Dictionary Derivation type】

Dictionary and set derivation is the continuation of the idea, the syntax is similar, but the result is a set and a dictionary. Its basic format is as follows:

{ key_expr:value_expr for value in collection if condition }

Example 1: using a dictionary derivation to build a dictionary with a string and its length

>>> strings = [' Import ', ' is ', ' was ', ' with ', ' if ', ' file ', ' exception ']>>> D = {Key:val to Val,key in enumerate ( strings)}>>> d{' exception ': 5, ' is ': 1, ' file ': 4, ' import ': 0, ' with ': 2, ' If ': 3}

" Set Deduction Formula "

The set deduction is very similar to the list derivation, except that the {} is the only difference. Its basic format is as follows:

{ expr for value in collection if condition }

Example 1: building a set of string lengths with set derivation

>>> strings = [' A ', ' is ', ' with ', ' if ', ' file ', ' exception ']>>> {len (s) for s in Strings}    # Having the same length will only leave one, which in fact is also very useful set ([1, 2, 4, 9])
" nested list derivation "

Nested lists are nested lists in a list, such as:

>>> L = [[4,5,6], [[         7,8,9]]
Example 1: a nested list of men's lists and women's lists, with names containing more than two letters E in their names, to form a list

names = [[' Tom ', ' Billy ', ' Jefferson ', ' Andrew ', ' Wesley ', ' Steven ', ' Joe '],         [' Alice ', ' Jill ', ' Ana ', ' Wendy ', ' Jennifer ', ' Sherry ', ' Eva ']

Implemented with A For loop:

TMP = []for lst in Names: for    name in LST:        if Name.count (' E ') >= 2:            tmp.append (name) print tmp# output >>& Gt [' Jefferson ', ' Wesley ', ' Steven ', ' Jennifer ']
implemented with nested lists:
>>> names = [[' Tom ', ' Billy ', ' Jefferson ', ' Andrew ', ' Wesley ', ' Steven ', ' Joe '],         [' Alice ', ' Jill ', ' Ana ', ' Wendy ', ' Jennifer ', ' Sherry ', ' Eva ']]>>> [name for LST in names for name in LST if Name.count (' E ') >=2]  #注意遍历 Order, which is the key to implementation [' Jefferson ', ' Wesley ', ' Steven ', ' Jennifer ']









An introduction to the derivation in Python

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.