- 写一个生成式能够产生的数据为: 1, 4, 27, 256, 3125,…, 9**9
[var ** var for var in range(1, 10)]
- 写一个生成式能够产生1-10中所有半径是偶数的圆的面积
[3.14 * radius ** 2 for radius in range(1, 11) if radius & 1 == 0]
- 写一个生成式交换字段的键和值,产生一个新的字典
{val: key for key, val in {1: 2, 3: 4, 5: 6}.items()}
- 为函数写一个装饰器,在函数执行之后输出 after
def decorator(f):
def wrapper(*args, **kwargs):
f(*args, **kwargs)
print('after')
return wrapper
- 为函数写一个装饰器,把函数的返回值 +100 然后再返回。
def decorator(f):
def wrapper(*args, **kwargs):
res = f(*args, **kwargs)
return res + 100
return wrapper
-
写一个装饰器@tag要求满足如下功能:
@tag def render(text): # 执行其他操作 return text @tag def render2(): return 'abc' print(render('Hello')) # 打印出: <p>Hello</p> print(render2()) # 打印出: <p>abc</p>
def tag(name: str='<p>'):
def decorator(f):
def wrapper(*args, **kwargs):
content = f(*args, **kwargs)
return '{tag}{content}{tag}'.format(tag=name, content=content)
return wrapper
return decorator
-
写一个装饰器@tag要求满足如下功能(需要使用带参的装饰器,自己先自学正在一下):
@tag(name='p') def render(text): # 执行其他操作 return text @tag(name='div') def render2(): return 'abc' print(render('Hello')) # 打印出: <p>Hello</p> print(render2()) # 打印出: <div>abc</div>
def tag(name: str='<p>'):
def decorator(f):
def wrapper(*args, **kwargs):
content = f(*args, **kwargs)
return '{tag}{content}{tag}'.format(tag=name, content=content)
return wrapper
return decorator
- 为函数写一个装饰器,根据参数不同做不同操作。
flag为True,则 让原函数执行后返回值加100,并返回。
flag为False,则 让原函数执行后返回值减100,并返回。
def selector(flag: bool=True):
def decorator(f):
def wrapper(*args, **kwargs):
res= f(*args, **kwargs)
return res + 100 if flag else res - 100
return wrapper
return decorator
- 写一个斗地主发牌器
import random
def dealer(num_of_people: int = 3, each_poker_num: int = 17):
def decorator(f):
def wrapper(*args, **kwargs):
pokers = f(*args, **kwargs)
for each in range(num_of_people):
hand_card = []
for _ in range(each_poker_num):
poker = random.select(pokers)
pokers.remove(poker)
hand_card.append(poker)
yield hand_card
else:
yield pokers
return wrapper
return decorator
@dealer()
def poker():
pokers = [for each in range(0 + 1, 13 + 1)] * 4
pokers.append('大王')
pokers.append('小王')
return pokers