A simple and practical formula for listing in Python

Source: Internet
Author: User
A list derivation is a way to create a new list with another list that works like A For loop:
>>> [x*x for X in range (10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
The list consists of the square of each x in range (10), and if you want to print only the squares that are divisible by 3? Then you can use the modulo operator--x%3, which returns 0 when the number can be divisible by 3:
>>> [x*x for x in range (ten) if x%3==0]
[0, 9, 36, 81]
You can also add more parts of the FOR statement:
>>> [(x, Y) for x in range (3) for Y in range (3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1)]


>>> x=[' waking ', ' in ', ' the ', ' Sun ']
>>> y=[' Today ', ' before ', ' silence '
>>> [B + ' + ' +g for B in X for G in Y if b[0]==g[0]]
[' The+today ', ' sun+silence ']

A simple and practical formula for listing 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.