简单替换for循环

它的主要语法结构如下:

  • my_list=[ 表达式 for 循环项 in 循环体 (if 条件) ]
  • 表达式可以为循环项,也可以为循环项的函数或者方法
name = "Donald Trump"
 
#list内的for循环语法,只使用一句代码
my_list = [c for c in name]
 
print(name)
print(my_list)



#  传统的for 循环语法是这么写的:

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








# 代码的作用是找出二维数组array(其实是list内嵌list)每一行的最小值,同样也只使用了一句代码

array = [[16, 3, 7],
          [2, 24, 9],
          [4, 1, 12]]
 
#表达式可以为循环项的函数
row_min = [min(row) for row in array ]
 
print(row_min)


list内的循环中使用if 条件

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)

更加复杂的表达式

names_list = ["washington", "trump", "obama", "bush", "clinton", "reagan"]
 
#将人名首字母大写
new_names = [name.capitalize() for name in names_list]
 
print(new_names)
  • my_list=[ 表达式(if...else 条件) for 循环项 in 循环体 ]
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)

嵌套for循环语法

names_list = ["Trump", "Obama","Clinton"]
 
#双重for循环
chars = [c for name in names_list for c in name]
 
print(chars)

使用生成器(Generator)变量来减少内存开销

#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)