zoukankan      html  css  js  c++  java
  • Python学习————函数作业

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

    def file_update(name, old_msg, new_msg):
        import os
        with open(f"{name}", "r", encoding="utf-8") as f, 
                open(f".{name}.swap", "w", encoding="utf-8") as f1:
            for line in f:
                f1.write(line.replace(old_msg, new_msg))
        os.remove(name)
        os.rename(f".{name}.swap", name)
    
    
    file_update("cvc.txt", "a", "b")
    

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

    def func(str):
        n = 0
        c = 0
        space = 0
        o = 0
        for i in str:
            if i.isdigit():
                n += 1
            elif i.isalpha():
                c += 1
            elif i.isspace():
                space += 1
            else:
                o += 1
        print(n, c, space, o)
    
    
    func('ads11  %')
    

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

    def fun1(n):
        print('判断传入对象的长度是否大于5')
        if len(n) >= 5:
            return True
        else:
            return False
    
    
    content = input('请输入:')
    print(fun1(content))
    

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

    def funtion(x):
        if len(x) > 2:
            return x[0:2]
    
    
    li = [1, 2, 3, 4, 5, 6, 7]
    print(funtion(li))
    

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

    def nmber(x):
        a = [x[i] for i in range(len(x)) if not i % 2 == 0]
        return a
    
    
    list = [0, 1, 2, 3, 4, 5, 6, 7, 8]
    b = nmber(list)
    print(b)
    

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

    PS:字典中的value只能是字符串或列表

    dic = {"a": "b", "c": [1, 2, 3, 4]}
    
    def dic2(dic):
        for i in dic:
            if len(dic[i]) > 2:
                dic[i] = dic[i][0:2]
        return dic
    
    res = dic2(dic)
    print(res)
    
  • 相关阅读:
    uva 11294 Wedding
    uvalive 4452 The Ministers’ Major Mess
    uvalive 3211 Now Or Later
    uvalive 3713 Astronauts
    uvalive 4288 Cat Vs. Dog
    uvalive 3276 The Great Wall Game
    uva 1411 Ants
    uva 11383 Golden Tiger Claw
    uva 11419 SAM I AM
    uvalive 3415 Guardian Of Decency
  • 原文地址:https://www.cnblogs.com/x945669/p/12521542.html
Copyright © 2011-2022 走看看