Learn Python comprehensions every day

Source: Internet
Author: User

Learn Python comprehensions every day
The derivation can simplify data processing and make the code concise and highly readable, which is very common in Python. List Derivation

List derivation allows you to perform a unified operation on all the elements in the list to obtain a new list (the original list does not change), as shown in[Processing Method for element in list]The processing method can be any operation:

>>> a=[1,2,3,4]>>> [i*2 for i in a][2, 4, 6, 8]>>> a[1, 2, 3, 4]>>> [(i*2,i+10) for i in a][(2, 11), (4, 12), (6, 13), (8, 14)]

You can filter out some elements in the original list by adding the if statement:

>>> a=[1,2,3,4]>>> [i*2 for i in a if i>2][6, 8]
Dictionary Derivation

We can create a dictionary through the derivation, but the dictionary derivation brackets are curly brackets:

>>> a[1, 2, 3, 4]>>> { "str"+str(i):i for i in a }{'str3': 3, 'str1': 1, 'str4': 4, 'str2': 2}

The dictionary derivation has a wonderful use, that is, the location where keys and values can be exchanged:

>>> a={'one':1,"two":2,"three":3}>>> {value:key for key,value in a.items()}{1: 'one', 2: 'two', 3: 'three'}

Note: Make sure that the value is also of an unchangeable type, such as a string or a tuples.

Set Derivation

The Set derivation is similar to the dictionary derivation, but there is only one value instead of the key-Value Pair:

>>> a={1,2,3,4,5}>>> {i**2 for i in a if i%2==1}{1, 9, 25}

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.