- 写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使 表自带的逆序函数)
def order(list1):
for x in range(len(list1) - 1):
for y in range(x + 1, len(list1)):
if list1[y] > list1[x]:
list1[x], list1[y] = list1[y], list1[x]
return list1
result=order([23,12,45,24,16,18,78])
print(result)
- 写一个函数,提取出字符串中所有奇数位上的字符
def odd(str):
list1=[]
for x in range(len(str)):
if x%2==0:
list1.append(str[x])
return list1
result=odd('stringwyndhnshdm')
print(result)
- 写一个匿名函数,判断指定的年是否是闰年?
year=lambda years : (years%4==0 and years%100 !=0) or years %400==0
print(year(2014))
# def year(n):
if n%4==0 and n%100 !=0:
return '%d 是闰年 ' % n
else:
return '%d 不是闰年' % n
result=year(2015)
print(result)
- 写函数,提去字符串中所有的数字字符。例如: 传入'ahjs233k23sss4k' 返回: '233234'
def cancel(str):
str1=''
for x in str:
if '0'<=x<='9':
str1+=x
return str1
result=str(cancel('ahjs233k23sss4k'))
print(result)
- 写一个函数,获取列表中的成绩的平均值,和最高分
def scores(list):
num1=sum(list)/len(list)
num2=max(list)
return '平均值成绩为:%d' %num1 ,'最高成绩为%d:'% num2
result=scores([90,85,98,86,50])
print(result )
- 写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调用者
def odd(list):
list1=[]
for x in range(len(list)):
if x%2==0:
list1.append(list[x])
return list1
result=odd()
print(result)
- 实现属于自己的字典update方法:用一个字典去更新另一个字典的元素(不能使用自带的update方法)
yt_update(字典1, 字典2)
def renewal(dict1,dict2):
for key1 in dict1:
for key2 in dict2:
if key1 == key2:
dict1[key1]=dict2[key2]
return dict1
else:
dict1[key2]
return dict1
result= renewal({'name': '张三', 'age': 30, 'score': 80},{'name': '李四', 'age': 30, 'score': 80})
print(result)
- 实现属于自己的items方法:将字典转换成列表,字典中的键值对转换成元祖。(不能使用items方法)
yt_items(字典)
例如:{'a': 1, 'b':2, 'c':3} ---> [('a', 1), ('b', 2), ('c', 3)]
def tuple1(dict1):
list1=[]
for key in dict1:
list1.append([key,dict1[key]])
return list1
result= tuple1({'name': '张三', 'age': 30, 'score': 80})
print(result)
- 有一个列表中保存的所有一个班的学生信息,使用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 big(dict1):
list1=[]
for item in all_student:
list1.append(item['score'])
max_score=max(list1)
if item['score'] == max_score:
return item
result= big(all_student)
print(result)
def smort(dict1):
list1=[]
for item in all_student:
list1.append(item['score'])
min_score=min(list1)
if item['score'] == min_score:
return item
result= smort(all_student)
print(result)