Compilation of tricks using for loop statements in python's List

The for loop is the most commonly used loop statement. It is frequently used in various high-level programming languages, and it is no exception in python. In addition to the conventional for loop or nested for loop syntax, python also has an exquisite list The syntax of the for loop statement. If you can master this syntax proficiently, it will be of great help to improve the efficiency of programming. Today I will share with you some tips I collected about using the for loop in the list. I hope it will help you Helpful:

1. Simply replace the for loop

Its main grammatical structure is as follows:

my_list=[expression for loop item in loop body (if condition)]

The expression here can be a loop item, or a function or method of a loop item. Let's see an example below:

name = "Donald Trump"

#list内的for循环语法,只使用一句代码
my_list = [c for c in name]

print(name)
print(my_list)

The traditional for loop syntax is written like this:

name = "Donald Trump"

#传统for循环语法,需要使用三句代码
my_list=[]
for c in name:
    my_list.append(c)
    
print(name)   
print(my_list)

Here, the traditional for loop needs to use three lines of code, while the for loop in the list only uses one line of code to achieve the same function. Let's look at another example:

array = [[16, 3, 7],
          [2, 24, 9],
          [4, 1, 12]]

#表达式可以为循环项的函数
row_min = [min(row) for row in array ]

print(row_min)

The function of the above code is to find the minimum value of each row of the two-dimensional array array (actually, the list is embedded in the list), and only one code is used.

2. Use the if condition in the loop inside the list

names_list = ["Washington", "Trump", "Obama", "bush", "Clinton", "Reagan"]
l1 = [name for name in names_list if name.startswith('W')]
l2 = [name for name in names_list if name.startswith('W') or len(name) < 5]
l3 = [name for name in names_list if len(name) < 5 and name.islower()]
print(l1, l2, l3)

We found that it is very convenient to use the if condition in the list loop. Here we use the if condition statement at the end of the for loop. If it is replaced with the traditional for loop syntax, it may add a lot of industry codes.

3. Use more complex expressions

names_list = ["washington", "trump", "obama", "bush", "clinton", "reagan"]

#将人名首字母大写
new_names = [name.capitalize() for name in names_list]

print(new_names)

Here the expression in our list uses the method capitalize() of the loop item name, let's look at another example:

my_list=[expression(if...else condition) for loop item in loop body]

names_list = ["Washington", "Trump", "Obama", "bush", "Clinton", "Reagan"]

#在表达式中使用if条件
new_names = [name if name.startswith('T') else 'Not President' for name in names_list]

print(new_names)

Previously we added the if condition at the end of the for loop, but we can also use the if condition statement in the expression. What needs to be pointed out here is that the else statement must be used in the if conditional statement in the expression, which is different from adding the if condition at the end of the for loop before, because the if statement in the expression must follow the rules for assigning values ​​to variables. Python syntax such as:

a = 1
b = 2 if a>0 # 语法错误

b = 2 if a > 0 else -1  

4. Use nested for loop syntax

You can use the nested for loop syntax in the list, let's look at an example below:

names_list = ["Trump", "Obama","Clinton"]

#双重for循环
chars = [c for name in names_list for c in name]

print(chars)

The following is a traditional two-level for loop statement:

names_list = ["Trump", "Obama","Clinton"]

#传统的双层for循环,需要使用4句代码
chars = []
for name in names_list:
    for c in name:
        chars.append(c)
        
print(chars)

We see that the traditional two-layer nested for loop needs to use 4 lines of code, while the double-layer for loop in the list only uses one line of code. Of course, the readability of traditional code is better than the loop statement in the list, so it is not recommended to add too many for loops in the list, which will make the readability of the code worse.

In addition, we can also use if conditions in the middle of two layers of for loops:

names_list = ["Trump", "Obama","bush"]

#可以在两层for循环的中间使用if条件
chars = [char for name in names_list if len(name) < 5 for char in name]

print(chars)

5. Try to avoid using built-in functions like map() and filter()

Python has some built-in functions such as map() and filter(). These built-in functions are easy to use, but have the disadvantages of poor readability and difficulty in understanding. A good habit is to use the for loop in the list to replace these built-in functions. Even the author of python recommends this, you can read this article ( https://www.artima.com/weblogs/viewpost.jsp?thread=98196 ), because doing so can make the code more readable good.

The map() function can be replaced like this:

#map function
L = map(func, loop body)

# Replace with:
L = [func(a) for a in loop body]

array = [[16, 3, 7],
          [2, 24, 9],
          [4, 1, 12]]

row_min = map(min, array)
print(list(row_min))

#替换为
row_min = [min(row) for row in array ]
print(row_min)

 

The filter() function can be replaced with:

#filter function
L = filter(condition_func, loop body)

# Replace with
L = [a for a in loop body if condition]

names_list = ["Trump", "Obama","bush"]

#filter函数
L1 = filter(lambda name: len(name) < 5, names_list)
print(list(L1))

#替换为:
L2 = [name for name in names_list if len(name) < 5]
print(L2)

6. Try to use generator (Generator ) variables to reduce memory overhead 

When defining a list variable in python, memory is generally allocated immediately to the list variable. This way of allocating memory immediately when defining a variable will increase the memory overhead of the system, and an efficient method is to only define the variable and not The actual memory is not allocated immediately, and the memory is only allocated when the variable is actually used. This is our Generator variable. When defining the Generator variable, just replace the square brackets of the original list with parentheses:

#list变量,立即分配实际内存
L1 = [x for x in range(1_000_000)]

#Generator变量,不分配实际内存
L2 = (x for x in range(1_000_000))
print(L1.__sizeof__())
print(L2.__sizeof__())

#list变量
L1 = [ w for w in range(10)]
for i in L1:
    print(i)

#替换为生成器变量
L2 = (w for w in range(10))
for i in L2:
    print(i)

in conclusion

Using the for loop in the list can make the code concise and elegant, and at the same time, the number of for loop layers in the list should not be increased too much, which will make the program less readable. We should try to use the for loop of list instead of built-in functions such as map and filter, because these built-in functions will also make the program less readable. Finally, we should try to use generator variables (Generator), because it can reduce memory overhead.

Guess you like

Origin blog.csdn.net/weixin_42608414/article/details/109923442