Examples of Python list generation and generator operations

  • 2020-12-05 17:17:21
  • OfStack

This article gives an example of Python list generation and generator operations. To share for your reference, the details are as follows:

List generation: Can be used to create list generation

Let's say I want to generate something like this [1*1,2*2,3*3,…..100*100] This kind of list when

You can use


[x * x for x in range(1,11)]

In addition to this, the filter can be filtered by adding judgment criteria later

Such as


[x * x for x in range(1,11) if x%2=0] 

This allows you to filter out squares with only even numbers

Multiple loops can also be used to generate perfect alignment


[m+n for m in 'ABC' for n in 'XYZ']

In short, list generation can be quickly generated to meet the conditions list

Here is an example of making all strings in list lowercase


[s.lower() for s in ['TIM','JOHN','MARY']

Generator: the list that is not finished loop, this is to save computer memory, set up a 1 side loop 1 side calculation mechanism.

The method of creation is also very simple, one of which is to generate the list [] to () It is ok

And you don't have to bother to call it next() Instead, use for Loop through

Such as:


g = (x*x for x in range(10))
for n in g:
  print(n)

Operation results:

[

0
1
4
9
16
25
36
49
64
81

]

This allows you to iterate over all the elements in the generator

Another method of a generator: if the function contains yield Keyword, this is a generator


def odd():
  print('step 1')
  yield 1
  print('step 2')
  yield(3)
  print('step 3')
  yield(5)

Use (traversal) method:


g=odd()
for i in g:
  print(i)

Operation results:

[

step 1
1
step 2
3
step 3
5

]

For more information about Python, please refer to Python list (list) operation Skills Summary, Python string operation skills Summary, Python Data Structure and Algorithm Tutorial, Python Function Use Skills Summary, Python Introduction and Advanced Classic Tutorial and Python File and Directory Operation Skills Summary.

I hope this article has been helpful in Python programming.


Related articles: