1.写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使列表自带的逆序函数)
def list_reverse(list1: list):
"""将指定的列表中的元素逆序"""
count = len(list1) - 1
for index in range(len(list1)):
if index < count:
list1[index], list1[count] = list1[count], list1[index]
count -= 1
else:
return list1
a = [1, 2, 3, 4, 5]
a = list_reverse(a)
print(a)
2.写一个函数,提取出字符串中所有奇数位上的字符
def get_odd_char(str1: str):
"""提取出字符串中所有奇数位上的字符"""
list1 = []
for index in range(len(str1)):
if index & 1 == 1:
list1.append(str1[index])
return list1
result = get_odd_char('f585geee8g45eg')
print('所有奇数为上的字符为:', result)
3.写一个匿名函数,判断指定的年是否是闰年
year = int(input('请输入要查询的年份:'))
leap_year = lambda year: (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
if leap_year(year) == True:
print('%d年是闰年' % year)
else:
print('%d年不是闰年' % year)
4.写函数,提去字符串中所有的数字字符。 例如: 传入'ahjs233k23sss4k' 返回: '233234'
def get_num(str1: str):
"""提去字符串中所有的数字字符"""
str2 = ''
for index in range(len(str1)):
if '0' <= str1[index] <= '9':
str2 += str1[index]
return str2
result = get_num('59feg95eg5gegh5e;eh5')
print(result)
5.写一个函数,获取列表中的成绩的平均值,和最高分
def average_max(list1: list):
return sum(list1) / len(list1), max(list1)
average, max1 = average_max([50, 80, 90, 100, 5, 60])
print('平均值为%.2f,最高分为%d' % (average, max1))
6.写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调用者
def odd_list(nums):
list1 = []
for index in range(len(nums)):
if index & 1 == 1:
list1.append(nums[index])
return list1
old_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_list = odd_list(old_list)
print(new_list)
7.实现属于自己的字典update方法:用一个字典去更新另一个字典的元素(不能使用自带的update方法) yt_update(字典1, 字典2)
def gyh_update(dict1, dict2):
for key in dict2:
dict1[key] = dict2[key]
return dict1
dict1 = {'a': 10, 'b': 20}
dict2 = {'a': 20, 'c': 100}
result = gyh_update(dict1, dict2)
print(result)
8.实现属于自己的items方法:将字典转换成列表,字典中的键值对转换成元祖。(不能使用items方法) yt_items(字典)
例如:{'a': 1, 'b':2, 'c':3} ---> [('a', 1), ('b', 2), ('c', 3)]
def gyh_items(dict1):
list1 = []
for key in dict1:
tuple1 = key, dict1[key]
list1.append(tuple1)
return list1
dict2 = {'a': 10, 'b': 20, 'c': 100}
result = gyh_items(dict2)
print(result)
9.有一个列表中保存的所一个班的学生信息,使用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}
]
注意: max和min函数也有参数key
all_students = [
{'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_students, key=lambda x: x['score']))
print(max(all_students, key=lambda x: x['age']))