python列表生成式

列表生成式


  • 列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。
# 方法一:
ls = list(range(1,10))

# 方法二
ls = [x for x in range(1,15)]

# 变形 求 x^2
ls = [x*x for x in range(1,15)] 

# 变形 求 x^2 且x为偶数
ls = [x*x for x in range(1,15) if x%2==0]

# 变形 求 x为偶数存放x^2,为奇数时存放x

ls = [x*x if x%2 == 0 else x for x in range(1,15)] 

# 再变 两个变量两个for
ls = [x+y for x in "ABC" for y in "XYZ"]

# 
ls = ['Hello', 'World', 'IBM', 'Apple']
ls = [s.lower() for s in ls]


# 练习  让所有的字符串变小写
L1 = ['Hello', 'World', 18, 'Apple', None]
ls = [x.lower() for x in L1 if type(x) is str]

print(ls)

你可能感兴趣的:(python,python,列表生成式)