Using a list-generated tutorial in Python _python

Source: Internet
Author: User

The list-generation, comprehensions, is a very simple, powerful build that Python can use to create a list.

For example, to generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] You can use range (1, 11):

>>> Range (1, one)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

But what if you want to generate [1x1, 2x2, 3x3, ..., 10x10]? Method one is loop:

>>> L = []
>>> for x in range (1, one):
...  L.append (x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

But a loop is too cumbersome, and a list-builder can use a single line of statements instead of looping to generate the list above:

>>> [x * x for x in range (1, one)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Write list generation, the element to be generated X * x into the front, followed by the For loop, you can create a list, very useful, more than a few times, you will soon be familiar with this syntax.

The For loop can also be followed by an if judgment so that we can filter out only the even squares:

>>> [x * x for x in range (1, one) if x 2 = 0]
[4, 16, 36, 64, 100]

You can also use a two-tier loop to generate a full arrangement:

>>> [M + N for m in ' ABC ' for n in ' XYZ ']
[' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']

A cycle of three and three layers is rarely used.

Using a list-generation, you can write very concise code. For example, listing all the file and directory names under the current directory can be done in one line of code:

>>> Import OS # importing OS modules, the concept of modules is described later in
>>> [D to D in Os.listdir ('. ')] # Os.listdir can list files and directories
['. emac S.D ', '. ssh ', '. Trash ', ' adlm ', ' applications ', ' Desktop ', ' Documents ', ' Downloads ', ' Library ', ' Movies ', ' Music ', ' Pictures ', ' public ', ' VirtualBox VMs ', ' Workspace ', ' XCode ']

For loops can actually use two or more variables at the same time, such as Dict's Iteritems () can iterate over key and value at the same time:

>>> d = {' X ': ' A ', ' y ': ' B ', ' z ': ' C '}
>>> for K, V in D.iteritems ():
...   Print k, ' = ', v ... 
y = B
x = A
z = C

As a result, list-generation can also use two variables to generate lists:

>>> d = {' X ': ' A ', ' y ': ' B ', ' z ': ' C '}
>>> [k + ' = ' + V for K, V in D.iteritems ()]
[' y=b ', ' X =a ', ' z=c ']

Finally, turn all strings in a list to lowercase:

>>> L = [' Hello ', ' World ', ' IBM ', ' Apple ']
>>> [S.lower () to S in L]
[' Hello ', ' World ', ' IBM ' , ' Apple ']

Summary

Using list generation, you can quickly generate lists, you can deduce another list from a list, but the code is very concise.

Thinking: If the list contains both a string and an integer, because the non-string type does not have the lower () method, the listing generates an error:

>>> L = [' Hello ', ' World ', #, ' Apple ', None]
>>> [S.lower () for S in L]
traceback (most recent Call last):
 File "<stdin>", line 1, in <module>
attributeerror: ' int ' object has no attribute ' lower '

Use the built-in Isinstance function to determine whether a variable is a string:

>>> x = ' abc '
>>> y = 123
>>> isinstance (x, str)
True
>>> Isinstance (y, str)
False

Modify the list generation to ensure that the list generation is executed correctly by adding an if statement.

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.