python推导式

一、列表推导式

例一:30以内所有能被3整除的数

multiples = [i for i in range(30) if i % 3 is 0]
print(multiples)
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
View Code

例二:30以内所有能被3整除的数的平方

def squared(x):
    return x*x
multiples = [squared(i) for i in range(30) if i % 3 is 0]
print(multiples)
View Code

例三:找到嵌套列表中名字含有两个‘e’的所有名字

names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
         ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]

print([name for lst in names for name in lst if name.count('e') >= 2])  # 注意遍历顺序,这是实现的关键
View Code

二、字典推导式

例一:将一个字典的key和value对调

mcase = {'a': 10, 'b': 34}
mcase_frequency = {mcase[k]: k for k in mcase}
print(mcase_frequency)
View Code

例二:合并大小写对应的value值,将k统一成小写

mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys()}
print(mcase_frequency)
View Code

三、集合推导式

例:计算列表中每个值的平方,自带去重功能

squared = {x**2 for x in [1, -1, 2]}
print(squared)
# Output: set([1, 4])
View Code

练习题:

例1:  过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母

l = ['namHe','ss','seFtfcSd','d','EThdyYhy']
print( [i.upper() for i in l if len(i) >=3])
例1答案

例2:  求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表

t1 = [(x,y) for x in range(6) if x % 2 is 0 for y in range(6) if y % 2 is 1]
print(t1)
例2答案

例3:  求M中3,6,9组成的列表M = [[1,2,3],[4,5,6],[7,8,9]]

 

M = [[1,2,3],[4,5,6],[7,8,9]]
m = [[x,y,z] for x in M[0] if x == 3 for y in M[0] if y == 6 for z in M[0] if z == 9]
print(m)
例3答案

 

posted @ 2018-02-07 16:04  三师弟悟净  阅读(212)  评论(0编辑  收藏  举报