day 9推导式和函数作业

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

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

    list1 = [x for x in range(1, 100) if x % 10 == 3]
    print(list1)    # [3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
    

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

    list1 = [True, 17, "hello", "bye", 98, 34, 21]
    list2 = [x for x in list1 if type(x) == int]
    print(list2)    # [17, 98, 34, 21]
    

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

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

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

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

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

    def sum1(n):
        sums = 0
        for x in range(1, n + 1):
            sums += n
        print(sums)
    
  3. 编写一个函数,求多个数中的最大值

    def max_num(*num):
        max_1 = num[0]
        for x in num:
            if max_1 < x:
                max_1 = x
        print(max_1)
    
  4. 编写一个函数,实现摇骰子的功能,打印N个骰子的点数和

    def dice_game(n):
        from random import randint
        sum1 = 0
        for _ in range(n):
            num = randint(1, 6)
            sum1 += num
        print(f'{n}次摇筛子点数和:',sum1)
    
    
    dice_game(3)
    
  5. 编写一个函数,交换指定字典的key和value。

dict1 = {'a': 1, 'b': 2, 'c': 3}


def exchange(dirt):
  new_dirt = {}
  for x in dirt:
      new_dirt[dirt[x]] = x
  print('dirt1 =', new_dirt)


exchange(dict1)     # dirt1 = {1: 'a', 2: 'b', 3: 'c'}
  1. 编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串

    str1 = '12a&bc12d-+'
    
    
    def get_word_orders(str):
        new_str = ''
        for x in str:
            if 'a' <= x <= 'z':
                new_str += x
        print(new_str)
    
    
    get_word_orders(str1)
    
  2. 写一个函数,求多个数的平均值

    def average(*num):
        sums = 0
        if len(num) == 0:
            mean_num = 0
        else:
            for x in num:
                sums += x
        mean_num = sums/len(num)
        print('平均数:', mean_num)
    
  3. 写一个函数,默认求10的阶乘,也可以求其他数字的阶乘

    def factorial(n=10):
        a = 1
        for x in range(1, n+1):
            a *= x
        print(f'{n}的阶乘为:{a}')
    
    
    factorial()     # 10的阶乘为:3628800
    

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

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

    def capitalize(str1):
        if str1:
            if 'a' <= str1[0] <= 'z':
                new_str = chr(ord(str1[0]) - 32) + str1[1:]
                print(new_str)
            else:
                print(str1)
        else:
            print(str1)
    
    
    capitalize('')
    capitalize('abc')   # Abc
    capitalize('12asd')    # 12asd
    
  2. 写一个自己的endswith函数,判断一个字符串是否以指定的字符串结束

def endswith(str1, str2):
 """
 判断一个字符串是否已指定的字符串结束
 :param str1:要判断的字符串
 :param str2:结尾字符串
 :return:None
 """
 if str1[-2:] == str2:
     print(True)
 else:
     print(False)


endswith('abc231ab', 'ab')  # True
endswith('abc231ab', 'ab1')  # False
  1. 写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
def isdigit(str1):
 count = 0
 for x in str1:
     if '1' <= x <= '9':
         count += 1
 if count == len(str1):
     print(True)
 else:
     print(False)


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

    def upper_(str1):
        list1 = list(str1)
        list2 = []
        for x in list1:
            if 'a' <= x <= 'z':
                list2.append(chr(ord(x) - 32))
            else:
                list2.append(x)
        print(''.join(list2))
    
    
    upper_('abH23好rp1')    # ABH23好RP1
    
  2. 写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充

def r_just(str1: str, width: int, fill_char: str):
 le = len(str1)
 # 处理指定宽度比原字符串宽度小
 if width < le:
     width = le
 # 处理字符长度不是1的情况
 if len(fill_char) != 1:
     raise ValueError
 new_str = fill_char*(width-le) + str1
 print(new_str)


r_just('abc', 7, '^')   # ^^^^abc
  1. 写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1

    def index_(list1, element):
        if element not in list1:
            print('-1')
        for x in range(len(list1)):
            if list1[x] == element:
                print(x, end=' ')
        print()
    
    
    index_([1, 2, 45, 'abc', 1, '你好', 1, 0], 1)    # 0 4 6
    
    index_(['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'], '赵云')    # 0 4 
    
    index_(['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'], '关羽')    # -1       
    
  2. 写一个自己的len函数,统计指定序列中元素的个数

    def len_(sequence, count=0):
        for x in sequence:
            count += 1
        print(f'该序列中有{count}个元素')
    
    
    len_([1, 3, 5, 6])  # 该序列中有4个元素
    len_((1, 34, 'a', 45, 'bbb'))   # 该序列中有5个元素
    len_('hello w')  # 该序列中有5个元素
    
  3. 写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值

    def max_(sequence):
        max_num = 0
        if type(sequence) == dict:
            for x in sequence:
                max_num = sequence[x]
                break
            for x in sequence:
                if sequence[x] > max_num:
                    max_num = sequence[x]
        if type(sequence) != dict:
            max_num = sequence[0]
            for x in sequence:
                if x > max_num:
                    max_num = x
        print(f'该序列中元素的最大值为:{max_num}')
    
    
    max_([-7, -12, -1, -9])     #该序列中元素的最大值为:-1
    max_('abcdpzasdz')      # 该序列中元素的最大值为:z
    max_({'小明': 90, '张三': 76, '路飞': 30, '小花': 98})      #该序列中元素的最大值为:98
    
  4. 写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在

    def in_(sequence, element):
        for x in sequence:
            if element == x:
                print(True)
                break
        else:
            print(False)
    
    
    in_((12, 90, 'abc'), '90')  # False
    in_([12, 90, 'abc'], 90)    # True   
    
  5. 写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串

    # 方法一
    
    
    # def replace_(str1, old_str, new_str):
    

list1 = str1.split(old_str)

#     new_str1 = new_str.join(list1)
#     print(new_str1)
#
#
# replace_('how are you? and you?', 'you', 'me')     # how are me? and me?

# 方法二


# def replace2(str1, old_str, new_str):
#     re_str = ''
#     index = 0
#     while index < len(str1):
#         if str1[index: index + len(old_str)] == old_str:
#             re_str += new_str
#             index += len(old_str)
#         else:
#             re_str += str1[index]
#             index += 1
#     print(re_str)
# 
# 
# replace2('how are you? and you?', 'you', 'me')    # how are me? and me?
```
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值