Learn Python more deeply with the old qi more understand the list

  • 2020-04-02 14:09:18
  • OfStack

The list parsing

Let's look at the following example, where you want to square each integer from 1 to 9, and print the result out in a list


>>> power2 = []
>>> for i in range(1,10):
...   power2.append(i*i)
... 
>>> power2
[1, 4, 9, 16, 25, 36, 49, 64, 81]

One of the most interesting features of python is list parsing, which looks like this:


>>> squares = [x**2 for x in range(1,10)]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81]

See this result, see an official still not awestruck? This is python, simple and elegant python!

Its official document has a description that illustrates the essence of list parsing:


List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

Remember that question from the previous lecture?

Find positive integers within 100 that are divisible by 3.
The method we use is:


aliquot = []

for n in range(1,100):
  if n%3 == 0:
    aliquot.append(n)

print aliquot

Ok. Now rewrite with list parsing, and it will look like this:


>>> aliquot = [n for n in range(1,100) if n%3==0]
>>> aliquot
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]

The shock. Absolutely awesome!

In fact, you can do this not only for a list of Numbers, but for all of them. Please calm the excited heart, silently look at the following code, feel the charm of list analysis.


>>> mybag = [' glass',' apple','green leaf ']  # Some have Spaces in front of them, some in the back 
>>> [one.strip() for one in mybag]       # Remove the Spaces before and after the element 
['glass', 'apple', 'green leaf']
enumerate

This is an interesting built-in function, because we could have gotten each element of a list for I in range(len(list)), and then gotten that element in list[I]. What if you want to get both element Numbers and elements? That's it:


>>> for i in range(len(week)):
...   print week[i]+' is '+str(i)   # Pay attention to, i is int Type, if used with the preceding + Connection, must be str type 
... 
monday is 0
sunday is 1
friday is 2

Python provides a built-in function enumerate that does something similar


>>> for (i,day) in enumerate(week):
...   print day+' is '+str(i)
... 
monday is 0
sunday is 1
friday is 2

It is an interesting built-in function, mainly to provide a quick and easy method.

The official document says:


Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

Copy a few examples by the way, for the official to appreciate, the best experiment.


>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Here we have something like (0,'Spring'), which is another data type, more on that later.


Related articles: