1.写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使 表自带的逆序函数)
def list_reverse(list1:list):
'''将列表元素逆序'''
return list1[::-1]
result = list_reverse([1, 2, 3, 4, 5])
print(result) # [5, 4, 3, 2, 1]
2写一个函数,提取出字符串中所有奇数位上的字符
def str_odd(str1:str):
'''提取字符串奇数位字符'''
str2 = ''
for index in range(0, len(str1), 2):
str2 += str1[index]
return str2
str1 = str_odd('abcdef')
print(str1) # bdf
3.写一个匿名函数,判断指定的年是否是闰
year_run = lambda year: '闰' if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else '不是闰年'
result = year_run(1200)
print(result) # 闰
4.写函数,提去字符串中所有的数字字符。
例如: 传入'ahjs233k23sss4k' 返回: '233234'
def str_num(str1:str):
"""提取字符串所有数字字符"""
str2 = ''
for item in str1:
if '0' <= item <= '9':
str2 += item
return str2
result = str_num('sdf222fdf443')
print(result) # 222443
6.写一个函数,获取列表中的成绩的平均值,和最高分
def list_score(list1:list):
"""获取列表成绩的平均成绩和最大值"""
sum1 = 0
for score in list1:
sum1 += score
return '平均成绩为%.2f,最高分为%.2f' % (sum1/len(list1), max(list1))
result = list_score([66, 77, 88, 99, 58])
print(result) # 平均成绩为77.60,最高分为99.00
7.写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调用者
def list_tuple(seq:list):
"""列表或元组的所有奇数位对应元素"""
list1 = []
for index in range(1, len(seq), 2):
list1.append(seq[index])
return list1
list_1 = list_tuple([0, 1, 2, 3, 4, 5, 6, 7])
print(list_1) # [1, 3, 5, 7]
tuple_1 = list_tuple((0, 1, 2, 3, 4, 5, 6, 7))
print(tuple_1) # [1, 3, 5, 7]
8.实现属于自己的字典update方法:用一个字典去更新另一个字典的元素(不能使用自带的update方法)
yt_update(字典1, 字典2)
def pu_update(dict_old:dict, dict_new:dict):
"""用新字典更新旧字典"""
for key in dict_new:
dict_old[key] = dict_new[key]
return dict_old
dict1 = pu_update({'a':10, 'b':20, 'c':30}, {'a':40, 'd':50})
print(dict1) # {'a': 40, 'b': 20, 'c': 30, 'd': 50}
9.实现属于自己的items方法:将字典转换成列表,字典中的键值对转换成元祖。(不能使用items方法)
yt_items(字典)
例如:{'a': 1, 'b':2, 'c':3} ---> [('a', 1), ('b', 2), ('c', 3)]
def pu_items(dict1:dict):
"""字典转换为列表,键值对转化为元组"""
list1 = []
for key in dict1:
list2 = []
list2.append(key)
list2.append(dict1[key])
list1.append(tuple(list2))
return list1
result = pu_items({'a':10, 'b':20, 'c':30})
print(result) # [('a', 10), ('b', 20), ('c', 30)]
10.有一个列表中保存的所一个班的学生信息,使用max函数获取列表中成绩最好的学生信息和年龄最大的学生信息
all_student = [
{'name': '张三', 'age': 19, 'score': 90},
{'name': 'stu1', 'age': 30, 'score': 79},
{'name': 'xiaoming', 'age': 12, 'score': 87},
{'name': 'stu22', 'age': 29, 'score': 99}
]
print(max(all_student, key= lambda item: item['score']))
# {'name': 'stu22', 'age': 29, 'score': 99}
print(max(all_student, key= lambda item: item['age']))
# {'name': 'stu1', 'age': 30, 'score': 79}
网友评论