1. 寫一個(gè)匿名函數(shù)姨丈,判斷指定的年是否是閏年
rui_year = lambda year:(year % 4 == 0 and year % 100 != 100) or year % 400 ==0
year = rui_year(2008)
print(year)
# def rui_year(year:int):
# return (year % 4 == 0 and year % 100 != 100) or year % 400 ==0
#
# year = rui_year(2008)
2.寫一個(gè)函數(shù)將一個(gè)指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使用列表自帶的逆序函數(shù))
# 方法5
def reverse_list(list1:list):
return list1[::-1]
b = reverse_list([1,2,3,4,5])
print(b) # [5, 4, 3, 2, 1]
# 方法1
reverse_list = lambda list1:list1[::-1]
print(reverse_list([1,2,3,4,5]))
# 方法2
list2 = [1,2,3,4,5]
print(list2[::-1])
# 方法3
list2.sort(reverse = True)
print(list2)
# 方法4
for index1 in range(len(list2)-1):
for index2 in range(index1+1,len(list2)):
if list2[index2]>list2[index1]:
list2[index1],list2[index2] = list2[index2],list2[index1]
print(list2)
3.寫一個(gè)函數(shù),獲取指定列表中指定元素的下標(biāo)(如果指定元素有多個(gè)瓦阐,將每個(gè)元素的下標(biāo)都返回)
例如: 列表是:[1, 3, 4, 1] ,元素是1, 返回:0,3
def get_index(list2:list,item):
item_index = []
for index in range(len(list2)):
if list2[index] == item:
item_index.append(index)
return item_index
c = get_index([1,3,4,1],1)
print(c)
4.寫一個(gè)函數(shù),能夠?qū)⒁粋€(gè)字典中的鍵值對(duì)添加到另外一個(gè)字典中(不使用字典自帶的update方法)
def add_dict(from_dict1:dict,to_dict:dict):
for key in from_dict1:
to_dict[key]=from_dict1[key]
return to_dict
d = add_dict({'a':1,'b':2,'c':3},{'d':4,'e':5})
print(d) # {'d': 4, 'e': 5, 'a': 1, 'b': 2, 'c': 3}
5.寫一個(gè)函數(shù)姆另,能夠?qū)⒅付ㄗ址械乃械男懽帜皋D(zhuǎn)換成大寫字母粟矿;所有的大寫字母轉(zhuǎn)換成小寫字母(不能使用字符串相關(guān)方法)
def exchage_func(str1:str):
exchage_str=''
for item in str1:
if 'a'<=item<='z':
item = chr(ord(item)-32)
elif 'A' <= item <= 'Z' :
item = chr(ord(item) + 32)
exchage_str += item
return exchage_str
e = exchage_func('123abcDEFG')
print(e)
6.實(shí)現(xiàn)一個(gè)屬于自己的items方法示弓,可以將自定的字典轉(zhuǎn)換成列表。列表中的元素是小的列表行冰,里面是key和value (不能使用字典的items方法)
例如:{'a':1, 'b':2} 轉(zhuǎn)換成 [['a', 1], ['b', 2]]
def exchange_list(dict3:dict):
list_big = []
for key in dict3:
list_small = [] # 每次循環(huán)列表都會(huì)清空一次
list_small.append(key)
list_small.append(dict3[key])
list_big.append(list_small)
return list_big
f = exchange_list({'a':1, 'b':2})
print(f)
7.寫一個(gè)函數(shù)溺蕉,實(shí)現(xiàn)學(xué)生的添加功能:
def add_stu_info():
print('======================添加學(xué)生=======================')
num = 0
stu_list = []
while True:
num += 1
stu_name = input('輸入學(xué)生姓名:')
stu_age = int(input('輸入學(xué)生年齡:'))
stu_tel = input('輸入學(xué)生電話:')
stu_id = str(num).rjust(3,'0') # 添加學(xué)號(hào)
print('===添加成功伶丐!')
stu_list.append({'name':stu_name,'age':stu_age,'tel':stu_tel,'id':stu_id})
result = int(input('1.繼續(xù)\n2.返回\n請(qǐng)選擇:'))
if result !=1:
return stu_list
a = add_stu_info()
print(a)