Python Learning -35.python list comprehensions (List explanation | list generation)

Source: Internet
Author: User
Tags python list

In some cases, we need to do something about the list, such as multiplying each element in the list by 2, which is generally the traversal of each element multiplied by 2. Then it will be two lines to write it down. And this will modify the original list, if you want to not modify the original list, there are more than one line.

1 mylist = [1,3,5,7]2 copylist = []3 for in mylist:  4     copylist.append (i * 2)5print(copylist)

One look is a bloated word.

Python provides a more straightforward way to do this:

1 mylist = [1,3,5,7]2 for in MyList]3print (mylist) 4 Print (copylist)

Output:

1 3 5 7

2 6 10 14

It's much easier to write like this. And it's easy to understand, first of all, for Elem in MyList this part is a loop--declaring elem temporary variable, traversing mylist list. The elem*2, however, indicates that the Elem temporary variable is multiplied by 2, and the last [] is well understood, because what we need is a list. The whole thing is to take the element from the MyList list, and return a list of each element multiplied by 2.

The power of the list explanation is not just that, it can also be conditional filtering:

1 mylist = [1,2,3,4,5,6,7,8,9,10]2forif elem% 2 = = 0]  3print(copylist)

Then this will output all the even two of the list.

In general, the list is interpreted with LINQ like in C #.

Python Learning -35.python list comprehensions (List explanation | list generation)

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.