'''
列表推导式:1.基本的使用方式
变量 = [变量或变量的处理结果 for 变量 in 容器类型数据]
'''
# 使用map和list计算数字平方
res = filter(lambda x:x,['wo',-2])
print(list(res))
re = map(lambda x:x**2 ,range(10))
print(re,type(re))
print(f'map和list完成{list(re)}')
# 使用普通方法完成
varlist = []
for i in range(10):
varlist.append(i ** 2)
print('普通函数完成',varlist)
# 运行结果:
# map和list完成[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 普通函数完成 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 下面是列表推导式 和第二中普通方法一样
varlist = [i **2 for i in range(10)]
print('列表推导式',varlist)
# '1234' =>[2,4,6,8] 练习题
varstr ='1234'
newlist = [int(i)*2 for i in varstr]
newlist = [print(int(i)*2) for i in varstr]
# 运行结果
# print(newlist)
# 2
# 4
# 6
# 8
# 还可以用位运算
newlist = [int(i)<<1 for i in varstr] #0001 =>0010
print('位运算',newlist)
# 结果:
# 位运算 [2, 4, 6, 8]
'''
二 带有判断条件的列表推导式
变量 = [变量或变量的处理结果 for 变量 in 容器类型数据 条件表达式]
'''
varlist = []
for i in range(10):
if i%2 ==0:
varlist.append(i)
print(varlist)
newlist = [i for i in range(10) if i%2==0]
newlist = [i**2 for i in range(10) if i%2==0]
print(newlist)
# [0, 2, 4, 6, 8]
# [0, 2, 4, 6, 8]
'''
三 带有多循环的推导式
'''
s1 = [1,2,3]
s2= [3,1,4]
listnew = [(i,j)for i in s1 for j in s2 if i != j ]
print(listnew)
# 运行结果
# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]