1.写函数,检查获取传入列表对象的所有奇数位索引对应的元素,并将其作为新列表返回
def func(l): return l[1::2] # 切片:列表、元祖、字符串等序列类的对象“隔几个”的取值,就用切片 print(func([1,2,3,4,5])) #[2,4]
2.写函数,判断用户传入的对象(字符串、列表、元祖)长度是否大于5
def func(x): return len(x)>5 print(func('abc')) #False
3.写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容并返回
# def func(l): # if len(l)>2: # return l[:2] # print(func([1,2,3,4,5])) # #[1,2] # print(func([1,2])) #None #当l长度小于等于2时结果是None #切片 当对象长度小于切片长度时,结果是对象本身而不是报错,代码可以简化且没有上面输出None的问题: def func(l): return l[:2] print(func([1,2,3,4])) #[1,2]
4.写函数,计算传入字符串中【数字】、【字母】、【空格】以及【其他】的个数,并返回结果
# def func(s): # num=0 #计算数字个数 # alpha=0 #字母 # space=0 #空格 # others=0 #其他 # for i in s: # if i.isdigit(): # num+=1 # elif i.isalpha(): # alpha+=1 # elif i.isspace(): # space+=1 # else:others+=1 # return num,alpha,space,others # print(func('abc 12322 @ 12as')) #用户看不懂输出内容的含义,只能看源码才能知道各数字的含义,体验不好,代码改为用字典输出: def func(s): dic = {'num': 0, 'alpha': 0, 'space': 0, 'others': 0} for i in s: if i.isdigit(): dic['num'] += 1 #键对应的值 elif i.isalpha(): dic['alpha'] += 1 elif i.isspace(): dic['space'] += 1 else: dic['others'] += 1 return dic print(func('abc 12322 @ 12as'))
5.写函数,检查用户传入的对象(字符串、列表、元祖)的每个元素是否含有空内容,并返回结果
这里的空内容值:‘avsd asdfgh’(字符串中的空格)
[1,2,3,4,'',[],(),'asd fdgg',' ',[''](列表中的元素是空字符串,空列表,空元祖;但元素是字符串时,里面有空格的不算;元素是字符串,里面是空格也不算,最后面两个元素都不算)
元祖同理)
def func(x): if not x:return True elif type(x) is str: for i in x: if i==' ': return True elif type(x) is list or type(x) is tuple: for i in x: if not i:return True print(func('1 23'),func(['a',[]])) #True,True