推导式
推导式的语法:
val for val in Iterable
三种方式:
[val for val in Iterable]
{val for val in Iterable}
{k,v for k,v in Iterable}
一、列表推导式
列表里面需要100条数据:
常规写法:
lst = []
for i in range(101):
lst.append(i)
print(lst)
列表推导式改写:
lst=[i for i in range(101)]
print(lst)
运行结果:
1、单循环推导式
将[1,2,3,4,5] 转为 [3,6,9,12,15]
常规写法:
lst = [1,2,3,4,5]
lst_new = []
for i in lst:
k = i * 3
lst_new.append(k)
print(lst_new)
列表推导式改写:
lst = [1,2,3,4,5]
lst_new=[i*3 for i in lst]
print(lst_new)
运行结果:
2、带有判断条件的单循环推导式
将列表中的偶数添加到新列表中:
lst = [1,2,3,4,5,6,7,8]
lst_new = []
for i in lst:
if i % 2 == 0:
lst_new.append(i)
print(lst_new)
列表推导式改写:
lst = [1,2,3,4,5,6,7,8]
lst_new=[i for i in lst if i % 2 == 0]
print(lst_new)
运行结果:
3、双循环推导式
将两个列表元组拼接成元组
lst1 = [1,3,5,7,9]
lst2 = [2,4,6,8,10]
lst_new = []
for k in lst1:
for v in lst2:
lst_new.append((k,v))
print(lst_new)
用列表推导式改写:
lst1 = [1,3,5,7,9]
lst2 = [2,4,6,