函数的参数-练习

1、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作

# 拓展:可以指定用户从前往后要修改的次数
def change_file(file_path, odd, new, modify_count):
    import os
    if not os.path.isfile(file_path):
        print('你要修改的文件不存在')
        return
    with open(file_path, mode='rt', encoding='utf-8') as f1, \
            open('swap.txt', mode='wt', encoding='utf-8') as f2:
        for line in f1:
            line = line.replace(odd, new, modify_count)
            f2.write(line)

2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

def statistics_type(data: str):
    """统计数据类型"""
    dic = {'number': 0, 'letter': 0, 'space': 0, 'other': 0}
    for symbol in data:
        if symbol.isdigit():
            dic['number'] += 1
        elif symbol.isalpha():
            dic['letter'] += 1
        elif symbol.isspace():
            dic['space'] += 1
        else:
            dic['other'] += 1
    print(dic)

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

def judge_len(obj):
    if len(obj) > 5:
        print('它的长度大于5')
    else:
        print('它的长度小于5')


# judge_len([1, 2, 3, 4, 5, 6, 7])  # 它的长度大于5
# judge_len((1, 2, 3, 4))   # 它的长度小于5
# judge_len('1234')  # 它的长度小于5

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

def processing_list(data: list):
    if len(data) > 2:
        return data[:2]
    return data


# res = processing_list([1, 2, 3])
# print(res)  # [1, 2]

# res = processing_list([1, 2])
# print(res)  # [1, 2]

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

def processing_container(data):
    """
    new_li = []
    for index in range(len(data)):
        if index % 2:  # 奇数除以2余1
            new_li.append(data[index])
    return new_li
    """
    # 优化:使用步长(总结:如果遇到“序列”类型的奇、偶问题,我们要想到步长的问题)
    return data[1::2]


# res = processing_container([1, 2, 3, 4, 5, 6, 7])
# print(res)  # [2, 4, 6]

# res = processing_container((1, 2, 3, 4, 5))
# print(res)  # [2, 4]

6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。(注意: 使用2种方法筛选区分可迭代对象, 与不可迭代对象)

  • 方法一: 调用collections.abc包中的功能Iterable + isinstance(obj, type)
def processing_dic(dic: dict):
    # 判断一个对象是否是可迭代对象
    from collections.abc import Iterable
    new_dic = {}

    for key, value in dic.items():
        if isinstance(value, Iterable):
            if len(value) > 2:
                if isinstance(value, list) or isinstance(value, str) or isinstance(value, tuple):
                    new_dic[key] = value[:2]
                else:
                    new_dic[key] = value
            else:
                new_dic[key] = value
        else:
            new_dic[key] = value
    return new_dic


res = processing_dic({'k1': 1, 'k2': 1.2, 'k3': None, 'k4': True, 'k5': [1, 2, 3, 4], 'k6': (1, 2, 3, 4, 5),
                      'k7': {'name': 'egon', 'sex': 'male'}, 'k8': 'hello World'})
print(res)  # {'k1': 1, 'k2': 1.2, 'k3': None, 'k4': True, 'k5': [1, 2], 'k6': (1, 2), 'k7': {'name': 'egon', 'sex': 'male', 'age': 18}, 'k8': 'he'}
  • 方法二: 使用可迭代对象iter() + try...except异常处理
def processing_dic(dic: dict):
    new_dic = {}
    for key, value in dic.items():
        try:
            iter(value)  # 如果value是不可迭代对象, 会报错TypeError, 通过捕捉这种错误达到区分可迭代对象, 与不可迭代对象
        except TypeError:
            new_dic[key] = value
            continue
        if len(value) > 2:
            # 只有字符串, 列表, 元组才能被切片取值
            if isinstance(value, list) or isinstance(value, str) or isinstance(value, tuple):
                new_dic[key] = value[:2]
            else:
                new_dic[key] = value
        else:
            new_dic[key] = value
    return new_dic

res = processing_dic({'k1': 1, 'k2': 1.2, 'k3': None, 'k4': True, 'k5': [1, 2, 3, 4], 'k6': (1, 2, 3, 4, 5),
                      'k7': {'name': 'egon', 'sex': 'male', 'age': 18}, 'k8': 'hello World'})
print(res)  # {'k1': 1, 'k2': 1.2, 'k3': None, 'k4': True, 'k5': [1, 2], 'k6': (1, 2), 'k7': {'name': 'egon', 'sex': 'male', 'age': 18}, 'k8': 'he'}
posted @ 2020-03-18 22:01  给你加马桶唱疏通  阅读(162)  评论(0编辑  收藏  举报