生成器 推导式 练习
2.用列表推导式做下列小题
过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母
lst = ["1","2","3","4","8","weeff","bdskjk","nsdjj"]
print([i.upper() for i in lst if len(i) > 3])
求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表
print([(x,y) for x in range(5) if x % 2 == 0 and ( for y in range(5) if y % 2 == 1) ])
求M中3,6,9组成的列表M = [[1,2,3],[4,5,6],[7,8,9]]
M = [[1,2,3],[4,5,6],[7,8,9]]
print([[i[-1]] for i in M ])
求出50以内能被3整除的数的平方,并放入到一个列表中。
print([i*2 for i in range(50) if i % 3 == 0])
构建一个列表lst = ['python1期', 'python2期', 'python3期', 'python4期', 'python6期', 'python7期', 'python8期', 'python9期', 'python10期']
print([f"python{i+1}期" for i in range(10) if i != 4])
构建一个列表:[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
print([(i, i+1) for i in range(6)])
构建一个列表:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
print([i for i in range(0,20,2)])
有一个列表l1 = ['alex', 'WuSir', '老男孩', '太白']将其构造成这种列表['alex0', 'WuSir1', '老男孩2', '太白3']
l1 = ['alex', 'WuSir', '老男孩', '太白'] #将其构造成这种列表['alex0', 'WuSir1', '老男孩2', '太白3']
print([f"{l1[i]}{i}" for i in range(len(l1))])
3.有以下数据类型:
x = {'name':'alex','Values':[{'timestamp':1517991992.94,'values':100,},{'timestamp': 1517992000.94,'values': 200,},
{'timestamp': 1517992014.94,'values': 300,},{'timestamp': 1517992744.94,'values': 350},{'timestamp': 1517992800.94,'values': 280}],}
# 将上面的数据通过列表推导式转换成下面的类型:
# [[1517991992.94, 100], [1517992000.94, 200], [1517992014.94, 300], [1517992744.94, 350], [1517992800.94, 280]]
lst = []
a = ([lst.append([x['Values'][i]['timestamp'],x['Values'][i]['values']]) for i in range(5)])
print(lst)
4.构建一个列表,列表里面是三种不同尺寸的T恤衫,每个尺寸都有两个颜色(列表里面的元素为元组类型)。
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
print([(x,y) for x in colors for y in sizes])
构建一个列表,列表里面的元素是扑克牌除去大小王以后,所有的牌类(列表里面的元素为元组类型)。
l1 = [('A','spades'),('A','diamonds'), ('A','clubs'), ('A','hearts')......('K','spades'),('K','diamonds'), ('K','clubs'), ('K','hearts') ]
l2 = ['A','2','3','4','5','6,''7','8','9','10','J','Q','K']
l3 = ["spades","diamonds","clubs","hearts"]
print([(x,y) for x in l2 for y in l3 ])
6.简述一下yield 与yield from的区别。
yield 单个返回,能够循环多次
yield from 将一个可迭代对象元素逐个返回
v = [i % 2 for i in range(10)]
print(v)
v = (i % 2 for i in range(10))
print(v) #生成器地址
for i in range(5):
print(i)
print()
0
1
2
3
4
4