A detailed explanation of the use of derivation in Python

Source: Internet
Author: User
Tags in python

This article mainly introduces the derivation of Python in the use of detailed, this article explains the list of derivation, dictionary derivation, set of the use of the derivation of examples, the need for friends can refer to the

The derivation is a powerful and popular feature in Python, with the advantages of simplicity, speed and so on. The derivation consists of:

1. List derivation type

2. Dictionary derivation type

3. Set Derivation type

Nested list derivation

Note: Dictionaries and collection derivations have only recently been added to Python (Python 2.7 and Python 3.1 versions). The following is a brief introduction:

"List-derived"

List derivation can be very concise to construct a new list: Only a concise expression can be used to transform the resulting elements of the transformation

The basic format is as follows:

The code is as follows:

[Expr for value in collection Ifcondition]

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

The code is as follows:

result = []

For value in collection:

If condition:

Result.append (expression)

Example 1: Filter out the list of strings with a length of less than 3 and convert the rest to uppercase

The code is as follows:

>>> names = [' Bob ', ' Tom ', ' Alice ', ' Jerry ', ' Wendy ', ' Smith ']

>>> [Name.upper () for name in names if Len (name) >3]

[' ALICE ', ' JERRY ', ' WENDY ', ' SMITH ']

Example 2: (X,y) where x is an even number between 0-5, and y is an odd-numbered Ganso list between 0-5

The code is as follows:

>>> [(X,y) for x in range (5) if x%2==0 to Y in range (5) if y%2==1]

[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]

Example 3: A list of 3,6,9 in M

The code is as follows:

>>> M = [[1,2,3],

... [4,5,6],

... [7,8,9]]

>>> M

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

>>> [row[2] for row in M]

[3, 6, 9]

#或者用下面的方式

>>> [m[row][2] for row in (0,1,2)]

[3, 6, 9]

Example 4: Find a list of 1,5,9 in M-slash

The code is as follows:

>>> M

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

>>> [M[i][i] for I in range (len (M))]

[1, 5, 9]

Example 5: Finding the product of matrices and elements in M,n

The code is as follows:

>>> M = [[1,2,3],

... [4,5,6],

... [7,8,9]]

>>> N = [[2,2,2],

... [3,3,3],

... [4,4,4]]

>>> [M[row][col]*n[row][col] for row in range (3) for Col in Range (3)]

[2, 4, 6, 12, 15, 18, 28, 32, 36]

>>> [[M[row][col]*n[row][col] for Col in Range (3)] for row in range (3)]

[[2, 4, 6], [12, 15, 18], [28, 32, 36]]

>>> [[M[row][col]*n[row][col] for row in range (3)] for Col in Range (3)]

[[2, 12, 28], [4, 15, 32], [6, 18, 36]]

Example 5: The age key in the dictionary, assigning a new value according to the condition

The code is as follows:

>>> Bob

{' Pay ': 3000, ' job ': ' Dev ', ' age ': ' Name ': ' Bob Smith '}

>>> Sue

{' Pay ': 4000, ' job ': ' HDW ', ' age ': ' Name ': ' Sue Jones '}

>>> people = [Bob, Sue]

>>> [rec[' age ']+100 if rec[' age '] >= (Else rec[' age ') for Rec in people] # Note for location

[42, 145]

"Dictionary derivation"

The dictionary and set derivation are the continuation of the idea, the grammar is similar, but only produces the collection and the dictionary. The basic format is as follows:

The code is as follows:

{key_expr:value_expr for value in collection if condition}

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

The code is as follows:

>>> strings = [' Import ', ' is ', ' with ', ' if ', ' file ', ' exception ']

>>> D = {Key:val for Val,key in Enumerate (strings)}

>>> D

{' Exception ': 5, ' is ': 1, ' file ': 4, ' import ': 0, ' with ': 2, ' If ': 3}

"Set-derived"

Collection derivations are very similar to list derivations, except that {} is substituted for []. The basic format is as follows:

The code is as follows:

{Expr for value in collection if condition}

Example 1: Deriving a set of string lengths with a set

The code is as follows:

>>> strings = [' A ', ' is ', ' with ', ' if ', ' file ', ' exception ']

>>> {len (s) for s in Strings} #有长度相同的会只留一个, which is also very useful in practice

Set ([1, 2, 4, 9])

"Nested list derivation"

A nested list refers to a list of nested lists, such as:

The code is as follows:

>>> L = [[1,2,3],

[4,5,6],

[7,8,9]]

Example 1: A nested list of men's and women's lists, taking out names with more than two letters E, composing lists

The code is as follows:

names = [[' Tom ', ' Billy ', ' Jefferson ', ' Andrew ', ' Wesley ', ' Steven ', ' Joe '],

[' Alice ', ' Jill ', ' Ana ', ' Wendy ', ' Jennifer ', ' Sherry ', ' Eva ']]

Implemented with A For loop:

The code is as follows:

TMP = []

For LST in Names:

For name in LST:

If Name.count (' E ') >= 2:

Tmp.append (name)

Print tmp

#输出结果

>>>

[' Jefferson ', ' Wesley ', ' Steven ', ' Jennifer ']

To implement with a nested list:

The code is as follows:

>>> 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] #注意遍历顺序, which is the key to implementation

[' Jefferson ', ' Wesley ', ' Steven ', ' Jennifer ']

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.