标签:multiple back lap pre eve alice class tput tom
列表推导式
例一: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]
例二:30以内所有能被3整除的数的平方
例三:找到嵌套列表中名字含有两个‘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]) # 注意遍历顺序,这是实现的关键
字典推导式
例一:将一个字典的key和value对调
mcase = {‘a‘: 10, ‘b‘: 34} mcase_frequency = {mcase[k]: k for k in mcase} print(mcase_frequency)
例二:合并大小写对应的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)
集合推导式
例:计算列表中每个值的平方,自带去重功能
练习题:
例1: 过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母
例2: 求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表
例3: 求M中3,6,9组成的列表M = [[1,2,3],[4,5,6],[7,8,9]]
1.[name.upper() for name in names if len(name)>3] 2.[(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1] 3. [row[2] for row in M]
标签:multiple back lap pre eve alice class tput tom
原文地址:http://www.cnblogs.com/dwenwen/p/7818570.html