Python list parsing and builder

Source: Internet
Author: User
Tags iterable python list

Security Code: Indifferent Childe


What is List parsing?

List resolution is the way to generate new lists efficiently based on existing lists

List parsing is an application of the Python iteration mechanism, which is often used to create new lists, so it is placed in []

Grammar:

[Expression for Iter_var in iterable]
[Expression for Iter_var in iterable if COND_EXPR]


Cases:

In [1]: L = [i**2-I in xrange (9)]

In [2]: Print L
[0, 1, 4, 9, 16, 25, 36, 49, 64]

Suppose you now have a list of list1, need to get the square of each element in the list list1, and generate a new list that you can do:

In [3]: List1 = [1,2,3,4,5,6,7,8]

In [4]: List2 = [i**2 for i in List1]

In [5]: Print List2
[1, 4, 9, 16, 25, 36, 49, 64]

Only the square of the computer whose element value is greater than or equal to 3 is List1, and a new list is generated, you can do this:

In [6]: List3 = [i**2 for i in List1 if I >= 3]

In [7]: Print List3
[9, 16, 25, 36, 49, 64]


List resolution can generate a new list based on an existing list in a way that is nearly one-fold faster than A for loop


The result of dividing the square of 10 numbers in the range of 1 to 10 by 2:

In [8]: For i in [i**2 for I in Xrange (1,11)]:
...: Print I/2
...:
0
2
4
8
12
18
24
32
40
50

Returns the result of dividing the square of all even squares by 2 in the range 1 to 10:

In [9]: For i in [i**2 for I in xrange (1,11) if I%2 = = 0]:
...: Print I/2
...:
2
8
18
32
50


Remove all files that end with. Log in the/root directory to generate a new list:

In [ten]: Import OS

In [all]: FileList = [I for I in Os.listdir ("/root") if I.endswith (". Log")]

In []: print filelist
[' Install.log ']

Take out all directories in the/etc directory and generate a new list:

in [+]: Directory1 = [i-I in Os.listdir ("/etc") if Os.path.isdir ("/etc/" +i)]

in [+]: Print Directory1
[' Pkcs11 ',  ' SASL2 ',  ' xml ',  ' pear ',  ' terminfo ',  ' "iSCSI ',  ' sysconfig ',  ' Security ',  ' statetab.d ',  ' NetworkManager ',  '. Java ',  ' rc4.d ',  ' gcrypt ',  ' xinetd.d ',  ' ssh ',  ' httpd ',  ' dhcp ',  ' php.d ',  ' rc6.d ',  ' rpm ',  ' cron.daily ',  ' Audit ',  ' SELinux ',  ' depmod.d ',  ' dracut.conf.d ',  ' ntp ',  ' xdg ',  ' init ',  ' Init.d ',  ' consolekit ',  ' pm ',  ' yum ',  ' openldap ',  ' sudoers.d ',,  ' LOGROTATE.D ',   ' LXC ',  ' PPP ',  ' ld.so.conf.d ',  ' rwtab.d ',  ' dbus-1 ',  ' gnupg ',  ' cron.weekly ',   ' SGML ',  ' PKI ',  ' rc2.d ',  ' modprobe.d ',  ' audisp ',  "Exim ',  ' blkid ',  ' PROFILE.D ',  ' cron.hourly ',  ' default ',  ' opt ',  ' rc0.d ',  ' SSL ',  ' fonts ',  ' SYSCTL.D ',  ' iproute2 ',  ' X11 ',  ' rc1.d ',  ', ' Plymouth ',  ' rc.d ',  ' yum.repos.d ',  ' Polkit-1 ',  ' cron.monthly ',   ' Pango ',  ' pam.d ',  ' rsyslog.d ',  ' prelink.conf.d ', ',  ' Alternatives ',  ' rc3.d ',  ' Makedev.d ',  ' popt.d ',  ' Docker ',  ' udev ',  ' gconf ',  ' LVM ',  ' cgconfig.d ',  ' CRON.D ',  ' chkconfig.d ',  ' bash_completion.d ',  "Skel ',  ' multipath ',  ' rc5.d ']


The For loop can also nest for loops when using list parsing. To illustrate:

Suppose you now have two lists List1 and List2, and now you want to implement the cross-multiplication of the elements of two lists, you can do this:

In []: List1 = [' x ', ' y ', ' Z ']

in [+]: List2 = [+]

in [+]: List3 = [(i,j) for I in List1 for J in List2]

in [+]: Print List3
[(' X ', 1), (' X ', 2), (' X ', 3), (' Y ', 1), (' Y ', 2), (' Y ', 3), (' Z ', 1), (' Z ', 2), (' Z ', 3)]


Next, you can do this when the element value in List2 is not crossed by the List1 by 1 o'clock:

in [+]: List4 = [(i,j) for I in List1 for J in List2 if J! = 1]

in [+]: Print List4
[(' X ', 2), (' X ', 3), (' Y ', 2), (' Y ', 3), (' Z ', 2), (' Z ', 3)]


List parsing returns a new list directly, and if there are a lot of elements in the original list, and the list parsing is growing up in geometric multiples, it will be extremely memory intensive, which would result in inefficiency.

However, after the list is generated, it is generally only one element at a time, and the for loop only iterates through one of the elements of the iteration at a time, based on which it is extremely bad to use a direct build of the list

Thus, we can make an extension to the list parsing, which is to turn [] into (), which is called the generator


The relationship between generator and list parsing is equivalent to the relationship between Xrange and range, which allows us to use an expression that generates only one value at a time, called lazy calculation.

The generator is not like a list resolution, no matter how you build it directly. The generator is simply called once, it can return one, call it again, and then return one.


The generator expression does not really create a list of numbers, but instead returns a generator object that "yields" the entry after each calculation of an entry. The generator expression uses a "lazy calculation" or a mechanism called "deferred evaluation".

When the sequence is too long and you need to get only one element at a time, you should consider using a builder expression instead of a list resolution

Generator expression Syntax:

(Expr for Iter_var in iterable)
(Expr for Iter_var in iterable if cond_expr)


Returns the square of all positive integers in the range 1 to 10:

in [+]: G1 = (i**2 for i in range (1,11))

In []: G1.next ()
OUT[22]: 1

In [All]: G1.next ()
OUT[23]: 4

In []: G1.next ()
OUT[24]: 9

in [+]: G1.next ()
OUT[25]: 16

in [+]: G1.next ()
OUT[26]: 25

in [+]: G1.next ()
OUT[27]: 36

In []: G1.next ()
OUT[28]: 49

In []: G1.next ()
OUT[29]: 64

in [+]: G1.next ()
OUT[30]: 81

In [to]: G1.next ()
OUT[31]: 100

in [+]: G1.next ()
---------------------------------------------------------------------------
Stopiteration Traceback (most recent)
<ipython-input-32-9066a8f18086> in <module> ()
----> 1 G1.next ()

Stopiteration:


Returns the result of dividing the square of all positive integers in the range 1 to 10 by 2:

In [all]: For I in (i**2 for I in range (1,11)):
...: Print I/2
...:
0
2
4
8
12
18
24
32
40
50

To generate offsets and elements, use the Enumerate function:

Range can be used to generate an index offset in a non-exhaustive traversal, not an element at the offset

If you need both an offset index and an offset element, you can use the enumerate () function, which returns a generator object, for example:

in [+]: url = ' www.python.org '

In [approx]: G2 = Enumerate (URL)

In [PNS]: G2.next ()
OUT[37]: (0, ' W ')

In []: G2.next ()
OUT[38]: (1, ' W ')

In [All]: G2.next ()
OUT[39]: (2, ' W ')

In [MAX]: G2.next ()
OUT[40]: (3, '. ')

in [+]: G2.next ()
OUT[41]: (4, ' P ')

In [All]: G2.next ()
OUT[42]: (5, ' Y ')

In []: G2.next ()
OUT[43]: (6, ' t ')

In []: G2.next ()
OUT[44]: (7, ' H ')

In [the]: G2.next ()
OUT[45]: (8, ' O ')

In []: G2.next ()
OUT[46]: (9, ' n ')

in [+]: G2.next ()
OUT[47]: (10, '. ')

In []: G2.next ()
OUT[48]: (One, ' O ')

in [+]: G2.next ()
OUT[49]: (+, ' r ')

in [[]: G2.next ()
OUT[50]: (+, ' g ')

In [Wuyi]: G2.next ()
---------------------------------------------------------------------------
Stopiteration Traceback (most recent)
<ipython-input-51-6d69cefe8ba3> in <module> ()
----> 1 G2.next ()

Stopiteration:


This is the list resolution and generator in Python! Only use this as a learning and growth record for Python.

This article from "Indifferent bo" blog, please be sure to keep this source http://itchentao.blog.51cto.com/5168625/1883103

Python list parsing and builder

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.