python_推导式

1、列表生成式

列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式列表生成式

#非列表生成式写法
list1=[]
for i in range(1,10):
    reult=i*i
    list1.append(reult)
print(list1)

#列表生成式
list2=[i*i  for i in range(1,10)]
print(list2)


D:\study\python\test\venv\Scripts\python.exe D:/study/python/test/dd.py
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[1, 4, 9, 16, 25, 36, 49, 64, 81]

2、三元表达式

三元表达式主要由三部分组成循环,条件判断,操作

 

例子:

#非三元式
list1=[]
for i in range(1,20):
    if i%2:
       list1.append(str(i).zfill(3))
print(list1)

#三元式
list2=[str(i).zfill(4) for i in range(1,20) if i%2]
print(list2)


D:\study\python\test\venv\Scripts\python.exe D:/study/python/test/dd.py
['001', '003', '005', '007', '009', '011', '013', '015', '017', '019']
['0001', '0003', '0005', '0007', '0009', '0011', '0013', '0015', '0017', '0019']

 

posted @ 2019-06-10 14:59  小戳同学  阅读(218)  评论(0编辑  收藏  举报