- 写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使 表自带的逆序函数)
def change_list(list1):
for index in range(len(list1)//2):
item = list1[index]
list1[index] = list1[-1 - index]
list1[-1 - index] = item
return list1
print(change_list([1, 2, 3, 4, 5]))
- 写一个函数,提取出字符串中所有奇数位上的字符
def jishu(str1):
for index in range(len(str1)):
if index % 2 == 1:
print(str1[index])
return str1[index]
print(jishu('asdfghj'))
- 写一个匿名函数,判断指定的年是否是闰
leap_year = lambda n: (n % 4 == 0 and n % 100 != 0) or n % 400 == 0
print(leap_year(1900))
- 写函数,提去字符串中所有的数字字符。
例如: 传入'ahjs233k23sss4k' 返回: '233234'
def remove_num(str1):
str2 = ' '
for index in range(len(str1)):
if '0' < str1[index] < '9':
str2 += str1[index]
return str2
print(remove_num('ahjs233k23sss4k'))
- 写一个函数,获取列表中的成绩的平均值,和最高分
def ave_max(list1):
max(list1)
ave_score = sum(list1) / len(list1)
print('最高成绩%d平均成绩%2f' % (max(list1), ave_score))
ave_max([90, 95, 80, 100])
- 写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调用者
def get_num(list1):
list2 = list(list1)
new_list = []
for index in range(len(list2)):
if index % 2 == 1:
new_list.append(list2[index])
return new_list
print(get_num([1, 3, 'c', 5, 'a', 'b']))
- 实现属于自己的字典update方法:用一个字典去更新另一个字典的元素(不能使用自带的update方法)
yt_update(字典1, 字典2)
def xy_update(dict1, dict2):
for index in dict2:
dict1[index] = dict2[index]
return dict1
print(xy_update({'name': 'xiaohua', 'color': 'black', 'height': 170}, {'height': 180, 'age': 18}))
- 实现属于自己的items方法:将字典转换成列表,字典中的键值对转换成元祖。(不能使用items方法)
yt_items(字典)
例如:{'a': 1, 'b':2, 'c':3} ---> [('a', 1), ('b', 2), ('c', 3)]
def xy_items(dict1):
list1 = []
for key in dict1:
tuple1 = key, dict1[key]
list1.append(tuple1)
return list1
print(xy_items({'a': 1, 'b':2, 'c':3}))
- 有一个列表中保存的所一个班的学生信息,使用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
def max_score(item):
return item['score']
def max_age(item):
return item['age']
print(max(all_student, key=max_score)) # 成绩最好
print(max(all_student, key=max_age)) # 年纪最大