Python练习(基础)

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

def func(lis):
    return lis[1::2]

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

def func(x):
    return len(x) > 5

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

def func(lis):
    if len(lis) > 2:
        return lis[:2]
但是切片有一个特性,多了不报错,所以可以这样写
def func(lis):
    return lis[:2]

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

def func(s):      # 'fsadsad432 edfd@#$'
    num = 0       # 计算数字的个数
    alpha = 0     # 字母
    space = 0     # 空格
    other = 0     # 其他

    for i in s:
        if i.isdigit():
            num += 1
        elif i.isalpha():
            alpha += 1
        elif i.isspace():
            space += 1
        else:
            other += 1
    return num,alpha,space,other

print(func('fsadsad432 edfd@#$'))

#结果
#(3, 11, 1, 3)

但是这样有个问题,就是没人知道你传回来的是什么,如果需要知道传回来的是什么,需要看源代码。所以最好要用字典。
def func(s):      # 'fsadsad432 edfd@#$'
    dic = {'num':0,'alpha':0,'space':0,'other':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['other'] += 1
    return dic

print(func('fsadsad432 edfd@#$'))

#结果
#{'alpha': 11, 'num': 3, 'other': 3, 'space': 1}

猜你喜欢

转载自www.cnblogs.com/dongye95/p/10015798.html