Python analytic style

Source: Internet
Author: User

One, List analytic type

List parsing is a pair of brackets outside, which returns a list.

The general form is: [Expr for item ' in itratoble]

Print ([i+1 for I in Range]) #结果: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
DEF Inc (X):    return X**2print ([Inc (I) for I in Range]) #结果: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print ([I for I in range] if i%2==0]) #结果: [0, 2, 4, 6, 8]

The filter () method takes a function and an iterator object to two parameters, returning a generator object.

List (filter (lambda x:x%2==0,range)) #结果: [0,2,4,6,8]

The map () method takes a function and an iterative object to two parameters, returning a list.

Map (Lambda X:x+1,range) #结果: [1,2,3,4,5,6,,7,8,9,10]

List parsing executes faster than filter () and map ().

Second, generator analytic type

The generator parsing is a pair of parentheses outside, which returns a generator object. It is calculated on demand or delayed.

The general form is: (Expr for item in itratoble)

(X for X in range (ten) if x%2==0)

Three, set analytic type

The set parsing is a pair of curly braces outside, which returns a collection, and it has all the characteristics of the collection.

The general form is: {Expr for item ' in hash-able object}

{x for x in range} #结果: {0,1,2,3,4,5,6,7,8,9}

Four, dictionary analytic style

The dictionary parsing is also a pair of curly braces outside, it requires two expressions, one generates a key, the other generates a value, and two expressions are separated by colons. So it returns a dictionary.

The general form is: {k:v for item in Itratoble}

Python-parsed

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.