- 写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使 表自带的逆序函数)
def list_reverse(list1):
lenth = len(list1)
index = lenth - 1
list2 = list1.copy()
for i in range(len(list1)):
list2[i] = list1[index]
index -= 1
print(list2)
list_reverse([1, 2, 3])
结果如下:
[3, 2, 1]
- 写一个函数,提取出字符串中所有奇数位上的字符
def take_alpha(str1):
print(str1[0:len(str1):2])
take_alpha('123456789')
结果如下:
13579
- 写一个匿名函数,判断指定的年是否是闰
def is_leap(num):
if num % 4 == 0 and num % 100 != 0 or num % 400 == 0:
print(num,' is a leap year')
else:
print(num,' is not a leap year')
is_leap(2012)
is_leap(2000)
结果如下;
2012 is a leap year
2000 is a leap year
- 写函数,提去字符串中所有的数字字符。
例如: 传入'ahjs233k23sss4k' 返回: '233234'
def take_number(str1):
str2 =''
for i in range(len(str1)):
if '0'<= str1[i] <= '9':
str2 += str1[i]
print(str2)
take_number('ahjs233k23sss4k')
结果如下;
233234
- 写一个函数,获取列表中的成绩的平均值,和最高分
def acl_list(list1):
sum = 0
max_grade = max(list1)
for items in list1:
sum += items
ave = sum / len(list1)
print('max grade is %.2f average grade is %2.f' %(max_grade,ave))
acl_list([90,92,95])
结果如下:
max grade is 95.00 average grade is 92
- 写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调用者
def new_list(list1):
list2 = []
for index in range(len(list1)):
if index %2 == 0:
list2.append(list1[index])
print(list2)
list3 = [1, 'a', [1,2,3], 'b']
new_list(list3)
结果如下:
[1, [1, 2, 3]]
- 实现属于自己的字典update方法:用一个字典去更新另一个字典的元素(不能使用自带的update方法)
yt_update(字典1, 字典2)
def sxc_update(dict1, dict2):
for items in dict2:
dict1[items] = dict2[items]
print(dict1)
dict1 = {'Name': 'Runoob', 'Age': 7}
dict2 = {'Sex': 'female'}
sxc_update(dict1, dict2)
结果如下:
{'Name': 'Runoob', 'Age': 7, 'Sex': 'female'}
- 实现属于自己的items方法:将字典转换成列表,字典中的键值对转换成元祖。(不能使用items方法)
yt_items(字典)
例如:{'a': 1, 'b':2, 'c':3} ---> [('a', 1), ('b', 2), ('c', 3)]
def sxc_items(dict1):
list1 = []
tuple1 = ()
for items in dict1:
tuple1 = (items, dict1[items])
list1.append(tuple1)
print(list1)
sxc_items({'a': 1, 'b':2, 'c':3})
结果如下:
[('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_key(list1, key):
list2 = []
for items in list1:
list2.append(items[key])
print(max(list2))
max_key(all_student, 'age')
结果如下:
30