推导式和函数作业

入门 N day

  1. 利用列表推导式, 完成以下需求:

    a. 生成一个存放1-100中各位数为3的数据列表:

    # 结果为 [3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
    lits1=[i for i in range(1,100) if i%10==3]
    print(lits1)
    

    b. 利用列表推到是将 列表中的整数提取出来:

    # 例如:[True, 17, "hello", "bye", 98, 34, 21] --- [17, 98, 34, 21]
    list1=[True, 17, "hello", "bye", 98, 34, 21]
    list2=[i for i in list1 if type(i) == int]
    print(list2)
    

    c. 利用列表推导式 存放指定列表中字符串的长度:

    # 例如 ["good", "nice", "see you", "bye"] --- [4, 4, 7, 3]
    list1=["good", "nice", "see you", "bye"]
    list2=[len(i) for i in list1]
    print(list2)
    

    d. dict_list = [{“科目”:“政治”, “成绩”:98}, {“科目”:“语文”, “成绩”:77}, {“科目”:“数学”, “成绩”:99}, {“科目”:“历史”, “成绩”:65}]

    去除列表中成绩小于70的字典 【列表推导式完成】

    # 结果为: [{“科目”:“政治”, “成绩”:98}, {“科目”:“语文”, “成绩”:77}, {“科目”:“数学”, “成绩”:99}]
    dict_list = [ {'科目':'政治', '成绩':98}, {'科目':'语文', '成绩':77},
                  {'科目':'数学', '成绩':99}, {'科目':'历史', '成绩':65}
                ]
    
    dict_list1=[grede for grede in dict_list if grede['成绩']>=70]
    print(dict_list1)
    
  2. 编写函数,求1+2+3+…N的和

    def my_sum(n):
        """
        求和
        :param n: 从1+到n
        :return: None
        """
        sums = 0
        for i in range(1, n + 1):
            sums += i
        print(f'它们的和是{sums}')
    
    
    my_sum(4)
    
  3. 编写一个函数,求多个数中的最大值

    def my_max(*nums):
        """
        求多个数的最大值
        :param nums: 提供多个数
        :return: 
        """
        max_num=0
        for i in nums:
            if i>max_num:
                max_num=i
        print(max_num)
    my_max(1,3,55,7,9)
    
  4. 编写一个函数,实现摇骰子的功能,打印N个骰子的点数和

    import random
    
    
    def my_sums(num):
        """
        实现摇骰子的功能,打印N个骰子的点数和
        :param num: 提供需要的骰子数
        :return:None
        """
        sums1 = 0
        for i in range(num):
            _num = random.randint(1, 6)
            sums1 += _num
            print(f'随机数是{_num}')
        print(f'它们的和是{sums1}')
    
    
    my_sums(3)
    
  5. 编写一个函数,交换指定字典的key和value。

# 例如:dict1={'a':1, 'b':2, 'c':3}  -->  dict1={1:'a', 2:'b', 3:'c'}  
def my_jh_dic():
  """
  交换字典中的键和值
  :return: None
  """
  dic1={'a':1, 'b':2, 'c':3}
  dic2=dict((i,dic1[i]) if type(dic1[i]) in (list,set,dict) else (dic1[i],i)  for i in dic1)
  print(dic2)
  
my_jh_dic()    
  1. 编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串

    # 例如: 传入'12a&bc12d-+'   -->  'abcd'  
    def my_zm_str():
        """
        拼接字母字符串
        :return: 	None
        """
        str1='dsA3216'
        str2='12354jl'
        str3=''
        
        for i  in str1 :
            if 'A'<=i <='Z'or 'a'<=i<='z':
                str3+=i
        for j  in str2 :
            if 'A'<=j <='Z'or 'a'<=j<='z':
                str3+=j
        print(str3)
    my_zm_str()
    
  2. 写一个函数,求多个数的平均值

    def my_mean(*args):
        """
         求多个数的平均值
        :param args: 提供多个数
        :return: None
        """
        means=sum(args)/len(args)
        print(means)
    
    my_mean(1,2,3,4,5)
    
  3. 写一个函数,默认求10的阶乘,也可以求其他数字的阶乘

    def my_factorial(num=10):
        """
        求一个数的阶乘
        :param num: 默认值是10,也可以是其他数
        :return: None
        """
        num1=1
        for i in range(1,num+1):
            num1*=i
        print(num1)
        
        
    my_factorial(3)
    

=======注意:以下方法不能使用系统提供的方法和函数,全部自己写逻辑

  1. 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母

    # 例如: 'abc' -> 'Abc'   '12asd'  --> '12asd'
    def my_capitalize(str1):
        """
        将指定字符串首字母变成大写字母
        :param str1: 提供字符串
        :return: None
        """
        if str1:
            if 'a'<=str1[0]<='z':
                dx_a = chr(ord(str1[0]) - 32)
                str2 = dx_a + str1[1:]
                print(str2)
            else:
                print(str1)
        else:
            print("空串")
    
    
    my_capitalize('abc')
    my_capitalize('12asd')
    my_capitalize('')
    
  2. 写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束

    # 例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True
    #     字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False
    def my_endswith(jw_str1, str2):
        """
        判断一个字符串是否以指定的字符串结束
        :param jw_str1: 提供结尾字符串
        :param str2: 提供需要判断的字符串
        :return: None
        """
        xb=-len(jw_str1)
        if jw_str1[-1]==str2[-1] and jw_str1[-1:0:-1]==str2[-1:xb:-1] :
            print(True)
        else:
            print(False)
    
    
    my_endswith('ab','abc2ab31ab')
    my_endswith('ab1','abc2ab31ab')
    
    
  3. 写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串

    例如: ‘1234921’ 结果: True
    ‘23函数’ 结果: False
    ‘a2390’ 结果: False

def my_isdigit(strs):
 """
 判断一个字符串是否是纯数字字符串
 :param strs: 提供需要判断的字符串
 :return: None
 """
 str1 = ''
 for num in strs:
     if'0' <= num <= '9':
         str1 += num
 if len(str1) == len(strs) :
     print(True)
 else:
     print(False)


my_isdigit('1234921')
my_isdigit('a2390')
my_isdigit('23函数')
 
  1. 写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母

    # 例如: 'abH23好rp1'   结果: 'ABH23好RP1'  
    def my_upper(strs):
        """
        将一个字符串中所有的小写字母变成大写字母
        :param strs: 提供一个字符串
        :return: None
        """
        str1=''
        for letter in strs:
            if 'a'<=letter<='z':
                letter=chr(ord(letter)-32)
            str1+=letter
        print(str1)
        
        
    my_upper('abH23好rp1')
                 
    
  2. 写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充

#  例如: 原字符:'abc'  宽度: 7  字符:'^'    结果: '^^^^abc'
#      原字符:'你好吗'  宽度: 5  字符:'0'    结果: '00你好吗'
def my_rjust(yzf_str,xzf_str,breadth):
 """
 在指定长度,原字符串在新字符串中右对齐,
 剩下的部分用指定的字符填充
 :param yzf_str:提供原字符串
 :param xzf_str:提供指定要添加的字符
 :param breadth:提供宽度
 :return:
 """
 if breadth<len(yzf_str):
     breadth=len(yzf_str)
 str3=xzf_str*(breadth-len(yzf_str))+yzf_str
 print(str3)
 
 
my_rjust(yzf_str='abc',xzf_str='*',breadth=7)
my_rjust(yzf_str='你好吗',xzf_str='0',breadth=5)                        
             
  1. 写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1

    '''
    例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0]  元素: 1   结果: 0,4,6  
         列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']  元素: '赵云'   结果: 0,4
         列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']  元素: '关羽'   结果: -1  
    '''
    def my_index(element, list2):
        """
        统计指定列表中指定元素的所有下标
        如果列表中没有指定元素返回 - 1
        :param element: 提供需要查找的元素
        :param list2:提供一个列表
        :return:None
        """
        if element in list2:
            lists = [i for i in range(len(list2)) if element == list2[i]]
            print(*lists)
        else:
            print(-1)
    
    
    my_index(1, [1, 2, 45, 'abc', 1, '你好', 1, 0])
    my_index('赵云', ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'])
    my_index('关羽', ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'])
           
    
  2. 写一个自己的len函数,统计指定序列中元素的个数

    '''
    例如: 序列:[1, 3, 5, 6]    结果: 4
         序列:(1, 34, 'a', 45, 'bbb')  结果: 5  
         序列:'hello w'    结果: 7
    '''
    
    def my_len(sequence):
        """
        统计指定序列中元素的个数
        :param sequence: 提供需要统计的序列
        :return: None
        """
        count = 0
        for i in sequence:
            count += 1
        print(count)
    
    
    my_len([1, 3, 5, 6])
    my_len((1, 34, 'a', 45, 'bbb'))
    my_len('hello w')
    
  3. 写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值

    '''
    例如: 序列:[-7, -12, -1, -9]    结果: -1   
         序列:'abcdpzasdz'    结果: 'z'  
         序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98}   结果: 98
    '''
    def my_max(sequence1):
        """
        获取指定序列中元素的最大值。
        如果序列是字典,取字典值的最大值
        :param sequence:提供一个序列
        :return:
        """
        if type(sequence1) == dict:
            sequence1 = sequence1.values()
        if type(sequence1) not in (list, tuple):
            sequence1 = list(sequence1)
        max_element = sequence1[0]
        for i in sequence1:
            if max_element <= i:
                max_element = i
    
        print(f'最大值:{max_element}')
    my_max([-7, -12, -1, -9])
    my_max('abcdpzasdz')
    my_max({'小明': 90, '张三': 76, '路飞': 30, '小花': 98})
    my_max({-7, -12, -1, -9})
       
    
    
    
    
    
    
    
    
    
  4. 写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在

    '''
    例如: 序列: (12, 90, 'abc')   元素: '90'     结果: False
         序列: [12, 90, 'abc']   元素: 90     结果: True 
    '''
    def my_in(strs,strs1):
        """
        判断指定序列中,指定的元素是否存在
        :param strs: 提供一个序列
        :param strs1: 提供一个指定元素
        :return: None
        """
        if type(strs)==dict:
            strs2=list(strs.keys())+list(strs.values())
            for i in strs2:
                if i == strs1:
                    num = True
                    break
                else:
                    num = False
            print(num)
        else:
            for i in strs:
                if i == strs1:
                    num = True
                    break
                else:
                    num = False
            print(num)
    my_in({'小明': 90, '张三': 76, '路飞': 30, '小花': 98},'小花')
    my_in({'小明': 90, '张三': 76, '路飞': 30, '小花': 98},98)
    my_in((12, 90, 'abc'),'90')
    my_in([12, 90, 'abc'],90)                
    
  5. 写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串
    例如: 原字符串: ‘how are you? and you?’ 旧字符串: ‘you’ 新字符串:‘me’ 结果: ‘how are me? and me?’

    # 方法一 利用字符串的函数先切割再添加
    def my_replace(strs, old_str, new_str):
        """
        将指定字符串中指定的旧字符串转换成指定的新字符串
        :param strs: 指定字符串
        :param old_str: 旧的字符串
        :param new_str: 新的字符串
        :return:None
        """
        lists = strs.split(old_str)
        new_strs = new_str.join(lists)
        print(new_strs)
    
    my_replace('how are you? and you?', 'you', 'me')    
    
    
# 方法二 
# 思路:利用while循环,定义一个下标,取一个字符判断后面连续字符是否与旧字符相等
# 不相等的就添加到新的字符串,同时下标加一位继续判断后面的字符
# 如果与旧字符相等,就替换为新字符,同时下标加旧字符的长度,继续判断后面的字符

def replace1(strs, old_str, new_str):
    new_str1 = ''
    o_len = len(old_str)
    index = 0
    while index < len(strs):
        if strs[index:len(old_str)+index]==old_str:
            new_str1+=new_str
            index+=o_len
        else:
            new_str1+=strs[index]
            index+=1
    print(new_str1)
    
    
replace1('how are you? and you?', 'you', 'me')




    
    
                      

    

    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值