names1 = ['Bob','Tom','alice','Jerry','Wendy','Smith'] # 对于长度超过3的名字,将其转换为大写, 并将结果存放到新列表中 names2 = [ name.upper() for name in names1 iflen(name)>3 ] print(f"names2: {names2}" )
# if 条件不是必须的 square_nums = [ x*x for x inrange(6) ] print( f"square nums: {square_nums}" )
# 可以拥有多个for语句 points1 = [ (x,y) for x inrange(2) for y inrange(3) ] print(f"points1: {points1}" )
# 可以拥有多个if语句。其会在for遍历后紧跟着进行条件判断 # 要求x坐标大于1、y坐标为奇数 points2 = [ (x,y) for x inrange(5) for y inrange(5) if x>1if y%2==1 ] print(f"points2: {points2}" ) # 要求x坐标为偶数、y坐标为奇数 points3 = [ (x,y) for x inrange(5) if x%2==0for y inrange(3) if y%2==1 ] print(f"points3: {points3}" )