练习函数

1、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者

1 def man(l):
2     return l[1::2]
3 print(man([5,6,8,43,2,2]))

2、写函数,判断用户传入的值(字符串、列表、元组)长度是否大于5

1 def of(x):
2    return  len(x) > 5  # 数字之间的判断返回的是Tuer或者False
3 if of("sada42"):
4     print("大于5了")

3、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者

1 def of(x):
2     return x[0:2]

4、写函数,计算传入字符串中【数字】、【字母】、【空格】 以及 【其他】的个数,并返回结果

 1 def func(s):
 2     dic = {'num':0,'alpha':0,'space':0,'other':0}
 3     for i in s:
 4         if i.isdigit():
 5             dic['num']+=1
 6         elif i.isalpha():
 7             dic['alpha'] += 1
 8         elif i.isspace():
 9             dic['space'] += 1
10         else:
11             dic['other'] += 1
12     return dic
13 print(func())

5、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容,并返回结果。

 1 def func(x):
 2     if type(x) is str and x:
 3         for i in x:
 4             if i == ' ':
 5                 return True
 6     elif x and type(x) is list or type(x) is tuple:
 7         for i in x:
 8             if not i:
 9                 return True
10     elif not x:
11         return True
12 
13 print(func())

6、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者

1 x={"a1":"v1v2","a2":"v3v4","a3":["asd","das","asdas"]}
2 def func(x):
3     for i in x:
4         if len(x[i])>2:
5          x[i]=x[i][0:2]
6         return x
7 print(func(x))

7、写函数,接收两个数字参数,返回比较大的那个数字

1 def max(a,b):
2     if a>b:
3         return a
4     elif b>a:
5         return b
6 print(max(3,8))

 8、批量将替换文件内容

1 def func(filename,old,new):
2     with open(filename,encoding='UTF-8') as a ,open('%s_the'%filename,"w",encoding="UTF-8") as a1 :
3         for i in a:
4             if old in i:
5                 i = i.replace(old,new)
6             a1.write(i)
7     import os
8     os.remove(filename)
9     os.rename('%s_the'%filename,filename)
原文地址:https://www.cnblogs.com/zxq520921/p/9393290.html