Three ways to count Python list production

Click on " Advanced Go Language Learning " above to follow

Reply to " Go Language " to receive a total of 10 e-books from beginner to advanced

now

day

Chickens

soup

When Xinglai goes alone, he knows nothing about victory.

I. Introduction

List comprehensions, namely List Comprehensions, are very simple but powerful built-in comprehensions in Python that can be used to create lists.

2. Case analysis

three methods

To generate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] you can use list(range(1, 11)).

print(list(range(1, 11)))

What if you want to generate [1x1, 2x2, 3x3, …, 10x10]?

1. Method one is looping:
L = []
for x in range(1, 11):
    L.append(x * x)
print(L)

But the loop is too cumbersome, and the list generation can use a line statement instead of the loop to generate the above list:

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

When writing a list production formula, put the element x * x to be generated in the front, followed by a for loop, and then you can create a list. It is very useful. Write it a few times and you will soon be familiar with this grammar.

You can also add an if judgment after the for loop, so that you can filter out only the square of even numbers:

for x in range(1, 11):
    L.append(x * x)


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

2. Using a two-layer loop, you can generate a full array
L = []
for x in range(1, 11):
    L.append(x * x)


print( [m + n for m in 'ABC' for n in 'XYZ'])

Three-tier and more than three-tier loops are rarely used.

3. Using list generation, you can write very concise code.

For example, to list all the file and directory names in the current directory can be achieved by one line of code:

import os  # 导入os模块,模块的概念后面讲到


print([d for d in os.listdir('.')])  # os.listdir可以列出文件和目录

The for loop can actually use two or more variables at the same time. For example, the items() of dict can iterate key and value at the same time:

d = {'x': 'A', 'y': 'B', 'z': 'C'}
for k, v in d.items():
    print(k, '=', v)

Therefore, the list comprehension can also use two variables to generate a list:

d = {'x': 'A', 'y': 'B', 'z': 'C' }
print([k + '=' + v for k, v in d.items()]

Finally, all strings in a list are changed to lowercase:

L = ['Hello', 'World', 'IBM', 'Apple']
print([s.lower() for s in L])

If the list contains both a string and an integer, since the non-string type has no lower() method, the list generation will report an error:

L = ['Hello', 'World', 18, 'Apple', None]
print([s.lower() for s in L])

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

x = 'abc'
y = 123
print(isinstance(x, str))


print(isinstance(y, str))

Three, practice and thinking

Please modify the list generation to ensure that the list generation can be executed correctly by adding an if statement.

# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2=???


# 期待输出: ['hello', 'world', 'apple']
print(L2)

Practice reference code:

L2 =[s.lower() for s in L1 if isinstance(s, str) ]

operation result:

Note:

Using the list generation formula, you can quickly generate a list, and you can derive another list from one list, but the code is very concise.

Four, summary

Based on the Python foundation, this article introduces the list generation formula, mainly based on cases, and explains three methods.

Analyze different methods to achieve the same effect. Provide effective solutions for points that need to be paid attention to and difficulties encountered in actual cases. Finally, through practice and thinking, deepen the understanding of list generation.

Everyone is welcome to try actively. Sometimes you see that it is easy for others to achieve, but when you do it yourself, there will always be various problems. Don't look at the master and work hard to understand more deeply.

The code is very simple, I hope it helps you learn.

------------------- End -------------------

Recommendations of previous wonderful articles:

Welcome everyone to like , leave a message, forward, reprint, thank you for your company and support

If you want to join the Go learning group, please reply in the background [ Enter the group ]

Thousands of rivers and mountains are always in love, can you click [ Looking ]

Guess you like

Origin blog.csdn.net/pdcfighting/article/details/113733209