- 写一个生成式能够产生的数据为: 1, 4, 27, 256, 3125,…, 9**9
num = (x ** x for x in range(1, 10))
- 写一个生成式能够产生1-10中所有半径是偶数的圆的面积
from math import pi
num = (pi * r ** 2 for r in range(1, 11) if r & 1 == 0)
- 写一个生成式交换字典的键和值,产生一个新的字典
dict1 = {'a': 1, 'b': 2}
dict2 =dict((dict1[key], key) for key in dict1)
- 为函数写一个装饰器,在函数执行之后输出 after
def after_tail(fn):
def tail(*args, **kwargs):
fn(*args, **kwargs)
print('after')
return tail
- 为函数写一个装饰器,把函数的返回值 +100 然后再返回。
def sum1(fn):
def sum_100(*args, **kwargs):
n = fn(*args, **kwargs)
n += 100
return n
return sum_100
-
写一个装饰器@tag要求满足如下功能:
@tag
def render(text):
# 执行其他操作
return text@tag
def render2():
return 'abc'print(render('Hello')) # 打印出: <p>Hello</p>
print(render2()) # 打印出: <p>abc</p>
def str1(fn):
def str_add(*args, **kwargs):
n = fn(*args, **kwargs)
n = '<p>' + n + '</p>'
return n
return str_add
-
写一个装饰器@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):
def str_add1(x):
def str_add(*args, **kwargs):
if name == 'p':
n = x(*args, **kwargs)
n = '<p>' + n + '</p>'
return n
if name == 'div':
n = x(*args, **kwargs)
n = '<div>' + n + '</div>'
return n
return str_add
return str_add1
- 为函数写一个装饰器,根据参数不同做不同操作。
flag为True,则 让原函数执行后返回值加100,并返回。
flag为False,则 让原函数执行后返回值减100,并返回。
def tag(flag):
def num_add1(x):
def num_add(*args, **kwargs):
if flag == True:
n = x(*args, **kwargs)
n += 100
return n
if flag == False:
n = x(*args, **kwargs)
n -= 100
return n
return num_add
return num_add1
- 写一个斗地主发牌器
import random
def poke_begin(poke):
poke = ['大王', '小王']
poke_nums = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
poke_flowers = ['♠', '♥', '♣', '♦']
for flowers in poke_flowers:
for nums in poke_nums:
poke.append(flowers + nums)
random.shuffle(poke)
player1 = []
player2 = []
player3 = []
dizhu = poke[51:]
print(dizhu)
for i in range(51):
if i % 3 == 0:
player1.append(poke[i])
if i % 3 == 1:
player2.append(poke[i])
else:
player3.append(poke[i])
print(player1)
print(player2)
print(player3)
return player1, player2, player3