1. 写一个匿名函数,判断指定的年是否是闰年
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.写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使用列表自带的逆序函数)
# 方法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.写一个函数,获取指定列表中指定元素的下标(如果指定元素有多个,将每个元素的下标都返回)
例如: 列表是:[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.写一个函数,能够将一个字典中的键值对添加到另外一个字典中(不使用字典自带的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.写一个函数,能够将指定字符串中的所有的小写字母转换成大写字母;所有的大写字母转换成小写字母(不能使用字符串相关方法)
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.实现一个属于自己的items方法,可以将自定的字典转换成列表。列表中的元素是小的列表,里面是key和value (不能使用字典的items方法)
例如:{'a':1, 'b':2} 转换成 [['a', 1], ['b', 2]]
def exchange_list(dict3:dict):
list_big = []
for key in dict3:
list_small = [] # 每次循环列表都会清空一次
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.写一个函数,实现学生的添加功能:
def add_stu_info():
print('======================添加学生=======================')
num = 0
stu_list = []
while True:
num += 1
stu_name = input('输入学生姓名:')
stu_age = int(input('输入学生年龄:'))
stu_tel = input('输入学生电话:')
stu_id = str(num).rjust(3,'0') # 添加学号
print('===添加成功!')
stu_list.append({'name':stu_name,'age':stu_age,'tel':stu_tel,'id':stu_id})
result = int(input('1.继续\n2.返回\n请选择:'))
if result !=1:
return stu_list
a = add_stu_info()
print(a)