1.列表推导式列表推导能非常简洁的构成一个新列表:只用一条简洁的表达式即可对得到的元素进行转换变形。

   格式:[表达式 for 变量 in 列表]或[表达式 for 变量 in 列表 if 条件]

   过滤条件可有可无,取决于实际应用,只留下表达式

>>> list =[x*x for x in range(10)]
相当于
>>> alist= []
>>> for x in range(10):
也相当于
>>> list= list(map(lambda x:x*x,range(10)))

2.阿凡提与国王比赛下棋,国王说要是izji输了的话阿凡提想要什么他都可以拿的出来。阿凡提说那就要点米吧,棋盘一共64个小格子,在第三个格子里放四粒米,第四个格子里放8粒米,以此类推,后面每个格子里的米都是前一个格子里的2倍,一直把64个格子都放满。需要多少粒米?

>>> sum([2**i for i in range(64)])
18446744073709551615

3.使用列表推导式实现嵌套列表的平铺

>>> vec=[[1,2,3],[4,5,6],[7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
相当于
>>> vec=[[1,2,3],[4,5,6],[7,8,9]] >>> result =[] >>> for elem in vec:   for num in elem:   result.append(num) >>> result [1,2,3,4,5,6,7,8,9]

4,如果不使用列表推导式,可以这样做。

>>> vec=[[1,2,3],[4,5,6],[7,8,9]]
>>> sum(vec,[])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> vec=[[1,2,3],[4,5,6],[7,8,9]]
>>> from itertools import chain
>>> list(chain(*vec))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

5.列出当前文件夹下所有python源文件

 

>>> import os
>>> [filename for filename in os.listdir('.')if filename.endswith(('.py','.pyw'))]

过滤不符合条件的元素
>>> list = [-1,-4,6,7,5,-2,3,9,-11]
>>>
>>> [i for i in list if i>0]
[6, 7, 5, 3, 9]

6.已知有一个包含一些同学成绩的字典,计算成绩的最高分、最低分、平均分,并查找所有最高分同学。

 

>>> scores={"zhangsan":45,"lisi":78,"wangwu":40,"zhouliu":96,"zhaoqi":65,"sunba":90,"zhengjiu":78,"wushi":99,"dongshiyi":60}
>>> heighest=max(scores.values())
>>> lowest = min(scores.values())>>> average=sum(scores.values())*1.0/len(scores)
>>> heighest,lowest,average
(99, 40, 72.33333333333333)
>>> heighestPerson=[name for name,score in scores.items()if score == heighest]
>>> heighestPerson
['wushi']

7.在列表推导式中使用多个循环,实现多序列元素组合,并且可以结合条件语句过滤特定元素

>>> [(x,y)for x in range(3) for y in range(2)]
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
>>> [(x,y) for x in [1,2,3]for y in [3,1,4]if x!=y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

 

 

 

 

 

 

 

 

 

posted on 2020-03-22 08:15  Lyon-w  阅读(1338)  评论(0编辑  收藏  举报