- 寫一個(gè)生成式能夠產(chǎn)生的數(shù)據(jù)為: 1, 2, 27, 256, 3125,…, 9**9
n = (x**x for x in range(1, 10))
for i in n:
print(i)
- 寫一個(gè)生成式能夠產(chǎn)生1-10中所有半徑是偶數(shù)的圓的面積
area = (x*x*3.14 for x in range(1, 11) if x % 2 ==0)
for i in area:
print(i)
- 寫一個(gè)生成式交換字段的鍵和值,產(chǎn)生一個(gè)新的字典
dict1 = {'a': 1, 'b': 2, 'c': 3}
dic_new = dict([val, key] for key, val in dict1.items())
print(dic_new)
- 為函數(shù)寫一個(gè)裝飾器冶伞,在函數(shù)執(zhí)行之后輸出 after
def decorate(fn):
def decor(*args, **kwargs):
print("after")
fn(*args, **kwargs)
return decor
@decorate
def func():
print("--------------")
func()
- 為函數(shù)寫一個(gè)裝飾器新症,把函數(shù)的返回值 +100 然后再返回。
def decorate(fn):
def dec(*args, **kwargs):
value = fn(*args, **kwargs)
return value + 100
return dec
@decorate
def func():
return 30
print(func())
- 寫一個(gè)裝飾器@tag要求滿足如下功能:
def tag(fn):
def tag1(*args, **kwargs):
value = fn(*args, **kwargs)
return "<p>" + str(value) + "</p>"
return tag1
@tag
def render(text):
return text
@tag
def render2():
return 'abc'
- 寫一個(gè)裝飾器@tag要求滿足如下功能(需要使用帶參的裝飾器碰缔,自己先自學(xué)正在一下):
def tag(name):
def middle(fn):
def last(*args, **kwargs):
values = fn(*args, **kwargs)
return "<"+name + ">" + values+"</"+name+">"
return last
return middle
@tag(name='p')
def render(text):
return text
@tag(name='div')
def render2():
return 'abc'
ren = render('Hello')
print(ren)
ren2 = render2()
print(ren2)
- 為函數(shù)寫一個(gè)裝飾器账劲,根據(jù)參數(shù)不同做不同操作。
flag為True,則 讓原函數(shù)執(zhí)行后返回值加100瀑焦,并返回腌且。
flag為False,則 讓原函數(shù)執(zhí)行后返回值減100榛瓮,并返回铺董。
def flag1(fn):
def flag2(*args, **kwargs):
values = fn(*args, **kwargs)
if values:
return values + 100
else:
return values - 100
return flag2
@flag1
def func(flag):
return flag
print(func(False))
- 寫一個(gè)斗地主發(fā)牌器
import random
list1 = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
list2 = ['黑桃', '紅桃', '方塊', '梅花']
cards = []
for col in list2:
for num in list1:
cards.append(col + num)
cards.append('大王')
cards.append('小王')
random.shuffle(cards) # 隨機(jī)打亂
print('user1:', cards[:17])
print('user2:', cards[17:34])
print('user3:', cards[34:51])
print('底牌:', cards[51:])