作业:Day10-函数基础

本文介绍了Python中字符串与列表的各种操作,包括如何创建字典映射、自定义join函数、检查字符串是否全为大写、清空列表、列表逆序以及替换子串。此外,还探讨了集合的交集运算和字典的更新方法,这些都是Python编程中常见的数据处理技巧。
  1. 写一个函数,实现maketrans的功能,将两个字符串转换成一个字典,第一个字符串中的字符是键,第二个字符串中的字符是值

    第一个字符串: ‘abcmn’ 第二个字符串:‘一二三四五’

    结果:{‘a’: ‘一’, ‘b’: ‘二’, ‘c’: ‘三’, ‘m’: ‘四’, ‘n’: ‘五’}

    # 方法一:
    def tran_dict(str1, str2):
        """通过遍历得到字符串下标,用字典推导式得到一个新的字典"""
        result = {str1[index]: str2[index] for index in range(len(str1))}
        return result
    
    
    print(tran_dict('abcmn', '一二三四五'))
    
    
    # 方法二:
    def tran_dict(str1, str2):
        """新建一个字典,一一赋值增加到字典中"""
        dict1 = {}
        for x in range(len(str1)):
            # 字典[键] = 值
            dict1[str1[x]] = str2[2]
        return dict1
    
    
    print(tran_dict('abcmn', '一二三四五'))
    
  2. 写一个属于自己的join函数,可以将任意序列中的元素以指定的字符串连接成一个新的字符串

    序列: [10, 20, 30, ‘abc’] 字符串: ‘+’ 结果:‘10+20+30+abc’

    序列: ‘abc’ 字符串: ‘–’ 结果:‘a–b--c’

    注意:序列中的元素可以不是字符串哟

    # 方法一:
    def me1_join(sequence, str1):
        """新建一个字符串,将两个字符串的元素按想要的位置加进去"""
        new_str = ''
        for x in sequence[:-1]:
            new_str += str(x) + str1
        result = new_str + str(sequence[-1])
        return result
    
    
    print(me1_join([10, 20, 30, 'abc'], '+'))
    
    
    # 方法二:
    def me2_join(sequence, str1):
        new_str = ''
        count = len(sequence)
        for x in sequence:
            new_str += str(x)
            count -= 1
            if count > 0:
                new_str += str1
        return new_str
    
    
    print(me2_join('abc', '--'))
    
  3. 写一个输入自己的upper函数,判断指定字符串是否是纯大写字母字符串

    ‘AMNDS’ -> True

    ‘amsKS’ -> False

    ‘123asd’ -> False

    def is_capital(str1):
        for x in str1:
            if not ('A' <= x <= 'Z'):
                # return False (return可以提前结束函数循环)
                print(False)
                break
        # return True
        else:
            print(True)
    
    
    is_capital('AMNDS')
    
  4. 写一个clear函数,清空指定列表。

    注意:功能是将原列表清空,不产生新的列表

    # 方法一:
    def clear_list(list1):
        for x in range(len(list1)):
            # del list1[0]
            del list1[-1]
        return list1
    
    
    print(clear_list([1, 2, 3, 4, 5]))
    
    
    # 方法二:
    def clear2_list(list1):
        for x in list1[:]:   # 拷贝一个列表
            list1.remove(x)
        return list1
    
    
    print(clear_list([1, 2, 3, 4, 5]))
    
  5. 写一个reverse函数,将列表中的元素逆序

    两种方法:1.产生一个新的列表 2.不产生新的列表,直接修改原列表元素的顺序

    # 方法一:
    def new_reverse(list1):
        new_list = []
        for x in list1[::-1]:
            new_list.append(x)
        # return list1[::-1]顶上面所有代码
        return new_list
    
    
    print(new_reverse([1, 2, 3, 4, 5]))
    
    
    # 方法二:
    def amend_reverse(list1):
        for index in range(len(list1)):
            """每次
            取出最后一个元素依次加到列表中"""
            list1.insert(index, list1.pop())
        return list1
    
    
    print(amend_reverse([1, 2, 3, 4, 5]))
    
  6. 写一个replace函数,将字符串中指定的子串替换成新的子串

    原字符串: ‘abc123abc哈哈哈uui123’ 旧子串: ‘123’ 新子串: ‘AB’

    结果: ‘abcABabc哈哈哈uuiAB’

    def replace(str1, old, new):
        """以旧子串为切割点切割,在用新子串join"""
        return new.join(str1.split(old))
    
    
    print(replace('abc123abc哈哈哈uui123', '123', 'AB'))
    
  7. 写一个函数,可以获取任意整数的十位数

    123 -> 2

    82339 -> 3

    9 -> 0

    -234 -> 3

    def tens(num):
        if num >= 0:
            return num // 10 % 10
        else:
            return -num // 10 % 10
    
    
    print(tens(-23511))
    
  8. 写一个函数实现数学集合运算符 & 的功能,求两个集合的公共部分:

    集合1: {1, 2, 3} 集合2: {6, 7, 3, 9, 1}

    结果:{1, 3}

    def intersection(set1, set2):
        new_set = set()
        for x in set1:
            if x in set2 not in new_set:
                new_set.add(x)
        return new_set
    
    
    print(intersection({1, 2, 3}, {6, 7, 3, 9, 1}))
    
  9. 写一个函数实现属于自己的字典update方法的功能,将一个字典中的键值对全部添加到另外一个字典中

    字典1: {‘a’: 10, ‘b’: 20} 字典2: {‘name’: ‘张三’, ‘age’: 18} -> 结果让字典1变成: {‘a’: 10, ‘b’: 20, name’: ‘张三’, ‘age’: 18}

    字典1: {‘a’: 10, ‘b’: 20} 字典2:{‘a’: 100, ‘c’: 200} -> 结果让字典1变成: {‘a’: 10, ‘b’: 20, ‘c’: 200}

    def update_dict(dict1, dict2):
        for key, value in dict2.items():
            if key not in dict1:
                dict1[key] = value
        return dict1
    
    
    print(update_dict({'a': 10, 'b': 20}, {'a': 100, 'c': 200}))
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值