码迷,mamicode.com
首页 > 其他好文 > 详细

练习函数

时间:2018-07-30 23:03:46      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:type   ret   and   man   获取   对象   检查   space   value   

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
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))

 

练习函数

标签:type   ret   and   man   获取   对象   检查   space   value   

原文地址:https://www.cnblogs.com/zxq520921/p/9393290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!