Learn the comprehensions of Python every day.

Source: Internet
Author: User

Learn the comprehensions of Python every day.

The derivation simplifies the processing of data, making the code simple and very readable at the same time. This is often seen in Python.

List-derived

The list derivation allows all elements in the list to be uniformly manipulated to obtain a completely new list (the original list does not change), in [处理方式 for 元素 in 列表] the form of which the processing can be done in whatever way:

>>>a=[1,2,3,4]>>>[i*2  forIincha][2,4,6,8]>>>a[1,2,3,4]>>>[(i*2, i+Ten) forIincha][(2, One), (4, A), (6, -), (8, -)]

The ability to filter out some elements of the original list by adding an If statement:

>>> a=[1,2,3,4]>>> [i*2forinif i>2][68]
Dictionary derivation type

We can create a dictionary by derivation, except that the parentheses of the dictionary derivation are curly braces:

>>> a[1234]>>> "str"forin a }{‘str3‘3‘str1‘1‘str4‘4‘str2‘2}

Using the dictionary derivation has a magical use, is the ability to exchange keys and values of the position:

a={‘one‘:1,"two":2,"three":3}>>> {valuefor key,valueina.items()}{1‘one‘2‘two‘3‘three‘}

Note: Ensure that values are immutable types, such as strings, tuples, etc.

Set Deduction formula

The set derivation is similar to the dictionary derivation. There is just one value instead of a key value pair:

>>> a={1,2,3,4,5}>>> {i**2forinif i%2==1}{1925}

Learn the comprehensions of Python every day.

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.