第二周python作业——字符串、字典、列表

字符串

基础

  1. 输入一个字符串,打印所有奇数位上的字符(下标是1,3,5,7…位上的字符)

    例如: 输入’abcd1234 ’ 输出’bd24’

    >>> a = 'abcd1234 '
    >>> a[1:-1:2]
    'bd24'
    
  2. 输入用户名,判断用户名是否合法(用户名长度6~10位)

    >>> str = input('请输入用户名:')
    请输入用户名:shfhruwhf
    >>> length=len(str)
    >>> if(6<=length<=10):
    ...     print('用户名为%10s,合法'%str)
    ... else:
    ...     print('用户名不合法')
    ...
    用户名为 shfhruwhf,合法
    
    >>> str = input('请输入用户名:')
    请输入用户名:qwertyuioplk
    >>> if(6<=length<=10):
    ...     print('用户名为%10s,合法'%str)
    ... else:
    ...     print('用户名不合法')
    ...
    用户名不合法
    
  3. 输入用户名,判断用户名是否合法(用户名中只能由数字和字母组成)

    例如: ‘abc’ — 合法 ‘123’ — 合法 ‘abc123a’ — 合法

    str = input('请输入用户名:')
    for i in str:
        if '0' <= i <= '9' or 'a' <= i <= 'z' or 'A' <= i <='Z':
            a = '用户名为%10s,合法'%str
        else:
            a = '用户名不合法' 
    
    请输入用户名:>? 123456ertffgf
    a
    Out[19]: '用户名为123456ertffgf,合法'
        
    请输入用户名:>? 12343g!@#$
    a
    Out[17]: '用户名不合法'
    
  4. 输入一个字符串,将字符串中所有的数字字符取出来产生一个新的字符串

    例如:输入**‘abc1shj23kls99+2kkk’** 输出:‘123992’

    str = input('请输入字符串:')
    b = ''
    for i in str:
        if '0' <= i <= '9':
            b += i
    print(b)
    
    请输入字符串:>? abc1shj23kls99+2kkk
    123992
    
  5. 输入一个字符串,将字符串中所有的小写字母变成对应的大写字母输出 (用upper方法和自己写算法两种方式实现)

    例如: 输入**‘a2h2klm12+’ ** 输出 ‘A2H2KLM12+’

    # upper
    str1 = input()
    str1 = str1.upper()
    print(str1)
    
    >? a2h2klm12+
    A2H2KLM12+
    
    # 算法
    str1 = input()
    str2 = ''
    for i in str1:
        if 'a' <= i <= 'z':
            str2 += chr(ord(i) - 32)
        else:
            str2 += i
    print(str2)
    
    >? a2h2klm12+
    A2H2KLM12+
    
  6. 输入一个小于1000的数字,产生对应的学号

    例如: 输入**‘23’,输出’py1901023’** 输入**‘9’, 输出’py1901009’** 输入**‘123’,输出’py1901123’**

    a = 'py190'
    num = input()
    b = 1000 + int(num)
    print(a,b,sep='')
    
    >? 123
    py1901123
    
  7. 输入一个字符串,统计字符串中非数字字母的字符的个数

    例如: 输入**‘anc2+93-sj胡说’** 输出:4 输入**‘===’** 输出:3

    str = input()
    count = 0
    for i in str:
        if '0' <= i <= '9' or 'a' <= i <= 'z' or 'A' <= i <='Z':
            continue
        else:
            count += 1
    print(count)
    
    >? anc2+93-sj胡说
    4
    >? ===
    3
    
  8. 输入字符串,将字符串的开头和结尾变成’+',产生一个新的字符串

    例如: 输入字符串**‘abc123’, 输出’+bc12+'**

    str = input()
    print('+',str[1:-1],'+',sep='')
    
    >? abc123
    +bc12+
    
  9. 输入字符串,获取字符串的中间字符

    例如: 输入**‘abc1234’** 输出:‘1’ 输入**‘abc123’** 输出**‘c1’**

    str = input()
    a = str[len(str) // 2] if len(str) % 2 != 0 else\
        str[len(str) // 2 - 1] + str[len(str) // 2]
    print(a)
    
    >? abc1234
    1
    >? abc123
    c1
    
  10. 写程序实现字符串函数find/index的功能(获取字符串1中字符串2第一次出现的位置)

    例如: 字符串1为:how are you? Im fine, Thank you! , 字符串2为:you, 打印8

    str1 = input()
    str2 = input()
    if str2 in str1:
        for i in range(len(str1) - len(str2) + 1):
            if str1[i: i + len(str2)] == str2:
                print(i)
                break
    else:
        print("ValueError")
    
    >? how are you? Im fine, Thank you!
    >? you
    8
    >? how are you? Im fine, Thank you!
    >? 12345
    ValueError
    
  11. 获取两个字符串中公共的字符

    例如: 字符串1为:abc123, 字符串2为: huak3 , 打印:公共字符有:a3

    str1 = input()
    str2 = input()
    b = ''
    for i in str1:
        if i in str2:
            b += i
    print('公共字符有:', b)
    
    >? abc123
    >? huak3
    公共字符有: a3
    
  12. 输入用户名,判断用户名是否合法(用户名必须包含且只能包含数字和字母,并且第一个字符必须是大写字母)

    例如: ‘abc’ — 不合法 ‘Mabc’ — 不合法 ‘123’ — 不合法 ‘abc123’ — 不合法 ‘Abc123ahs’ — 合法

    username = input('请输入用户名:')
    if 'A' <= username[0] <= 'Z':
        count = 0  
        for x in username[1:]:
            if not ('0' <= x <= '9' or 'a' <= x <= 'z' or 'A' <= x <= 'Z'):
                print('不合法')
                break
            else:
                if '0' <= x <= '9':
                    count += 1
        else:
            if count:
                print('用户名合法!')
            else:
                print('不合法')
    else:
        print('不合法')
    
    请输入用户名:>? abc
    不合法
    请输入用户名:>? Mabc
    不合法
    请输入用户名:>? 123
    不合法
    请输入用户名:>? abc123
    不合法
    请输入用户名:>? Abc123ahs
    用户名合法!
    

进阶

  1. 编写一个程序,交换指定字典的key和value。

      例如:dict1={'a':1, 'b':2, 'c':3}  -->  dict1={1:'a', 2:'b', 3:'c'} 
    
    dict1={'a':1, 'b':2, 'c':3}
    dict2 = {}
    for i,j in dict1.items():
        dict2[j] = i
    print(dict2)
    
    {1: 'a', 2: 'b', 3: 'c'}
    
  2. 编写一个程序,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串

       例如: 传入'12a&bc12d-+'   -->  'abcd'  
    
    str1 = '12a&bc12d-+'
    str2 = ''
    for i in str1:
        if i.isalpha():
            str2+=i
    print(str2)
    
    abcd
    
  3. 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母

      例如: 'abc' -> 'Abc'   '12asd'  --> '12asd'
    
    str1 = input('请输入字符串:')
    if 'a'<=str1[0]<='z':
        str1 = str1[0].upper()+str1[1:]
        print(f'首字母大写为{str1}')
    else:
        print(str1)
    
    请输入字符串:12asd
    首字母大写为12asd
    
  4. 写程序实现endswith的功能,判断一个字符串是否已指定的字符串结束

       例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True
            字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False
    
    str1 = input('请输入字符串:')
    str2 = input('请输入结束字符串:')
    if str1[-len(str2):] == str2:
        print('True')
    else:
        print('False')
    
    >>> str2 = input('请输入结束字符串:')
    请输入结束字符串:ab
    ...
    True
    >>> str2 = input('请输入结束字符串:')
    请输入结束字符串:ab1
    ...
    False
    
  5. 写程序实现isdigit的功能,判断一个字符串是否是纯数字字符串

       例如: '1234921'  结果: True
             '23函数'   结果: False
             'a2390'    结果: a2390
    
    str1 = input('请输入字符串:')
    for i in str1:
        if not '0'<=i<='9':
            print('False')
            break
    else:
        print('True')
    
    
    请输入结束字符串:1234921
    True
    请输入结束字符串:23函数
    False
    请输入结束字符串:a2390
    False
    
  6. 写程序实现upper的功能,将一个字符串中所有的小写字母变成大写字母

        例如: 'abH23好rp1'   结果: 'ABH23好RP1'   
    
    >>> str1 = input('请输入字符串:')
    请输入字符串:abH23好rp1
    >>> str2 = ''
    >>> for i in str1:
    ...     if 'a'<=i<='z':
    ...         str2+=chr(ord(i)-32)
    ...     else:
    ...         str2+=i
    ...
    >>> str2
    'ABH23好RP1'
    
  7. 写程序获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值

       例如: 序列:[-7, -12, -1, -9]    结果: -1   
            序列:'abcdpzasdz'    结果: 'z'  
            序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98}   结果: 98
    
    >>> object = [-7, -12, -1, -9]
    >>> if type(object) == dict:
    ...     print(max(object.values()))
    ... else:
    ...     print(max(object))
    ...
    -1
    
    >>> object = 'abcdpzasdz'
    ...
    z
    >>> object = {'小明':90, '张三': 76, '路飞':30, '小花': 98}
    ...
    98
    
  8. 写程序实现replace函数的功能,将指定字符串中指定的旧字符串转换成指定的新字符串

        例如: 原字符串: 'how are you? and you?'   旧字符串: 'you'  新字符串:'me'  结果: 'how are me? and me?'
    
    >>> str_1 = 'how are you, and you?'
    >>> str_2 = 'you'
    >>> str_3 = 'me'
    >>> str_4 = ''
    >>> i = 0
    >>> while i < len(str_1):
    ...      if str_2 == str_1[i: i + len(str_2)]:
    ...          str_4 += str_3
    ...          i += len(str_2)
    ...      else:
    ...          str_4 += str_1[i]
    ...          i += 1
    ...
    >>> str_4
    'how are me, and me?'
    
  9. 写程序实现split的功能,将字符串中指定子串作为切割点对字符串进行切割

    例如:原字符串: 'how are you? and you?'   切割点: 'you'  结果: ['how are ', '? and ', '?']
    
    >>> str1 = 'how are you? and you?'
    >>> str2 = 'you'
    >>> lis = []
    >>> while True:
    ...     for i in range(len(str1)):
    ...         if str1[i:i+len(str2)] == str2:
    ...             lis.append(str1[:i])
    ...             break
    ...     str1 = str1[i+len(str2):]
    ...     if str2 not in str1:
    ...         lis.append(str1)
    ...         break
    ...
    >>> lis
    ['how are ', '? and ', '?']
    

字典

  1. 定义一个变量保存一个学生的信息,学生信心中包括:姓名、年龄、成绩(单科)、电话、性别

    stu = {'name': '小明', 'age': 18, 'score': 99, 'tel': '1812727823', 'gender': '男'}
    print(stu)
    
  2. 定义一个列表,在列表中保存6个学生的信息(学生信息中包括: 姓名、年龄、成绩(单科)、电话、性别(男、女、不明) )

    students = [
        {'name': 'stu1', 'age': 23, 'score': 56, 'tel': '1812727822', 'gender': '男'},
        {'name': 'stu2', 'age': 27, 'score': 77, 'tel': '1812727823', 'gender': '女'},
        {'name': 'stu3', 'age': 20, 'score': 81, 'tel': '1812727828'},
        {'name': 'stu4', 'age': 16, 'score': 63, 'tel': '1812727888', 'gender': '男'},
        {'name': 'stu5', 'age': 22, 'score': 81, 'tel': '18127278289', 'gender': '女'},
        {'name': 'stu6', 'age': 15, 'score': 59, 'tel': '18127278091'}
    ]
    
    1. 统计不及格学生的个数

      count = 0
      for stu in students:
          if stu.get('score', 0) < 60:
              count += 1
      print('不及格学生的个数:', count)
      
    2. 打印不及格未成年学生的名字和对应的成绩

      print('不及格未成年学生的名字和对应的成绩:', end=' ')
      for stu in students:
          if stu['score'] < 60 and stu['age'] < 18:
              print(stu['name'], stu['score'])
      
    3. 求所有男生的平均年龄

      total_age = m_count = 0
      for stu in students:
          if stu.get('gender') == '男':
              total_age += stu['age']
              m_count += 1
      print('所有男生的平均年龄:', total_age / m_count)
      
    4. 打印手机尾号是8的学生的名字

      names = [stu['name'] for stu in students if stu['tel'][-1] == '8']
      print('手机尾号是8的学生的名字:', names)
      
    5. 打印最高分和对应的学生的名字

      # 方法一:
      max_score = student[0]['score']
      names = [stu['name'] for stu in students if stu['score'] == max_score]
      print('最高分和对应的学生的名字:', max_score, names)
      
      # 方法二:
      max_score = students[0]['score']
      names = [student[0]['name']]
      for stu in students[1:]:
          if stu['score'] > max['score']:
              max_socre = stu['score']
              names.clear()
              names.append(stu['name'])
      	elif stu['score'] == max_score:
              names.append(stu['name'])
      print('最高分和对应的学生的姓名:', max_score, names)
      
    6. 删除性别不明的所有学生

      # 方法一
      for stu in students[:]:
          if not stu.get('gender'):
              students.remove(stu)
      print(students)
      
      # 方法二
      new_students = [stu for stu in students if stu.get('gender')]
      print(new_students)
      
    7. 将列表按学生成绩从大到小排序(挣扎一下,不行就放弃)

      students.sort(key=lambda item: item['score'])
      print(students)
      
  3. 定义一个变量保存一个班级的信息,班级信息中包括:班级名称、教室位置、班主任信息、讲师信息、班级所有的学生(根据实际情况确定数据类型和具体信息)

    class1 = {
        'class_name': 'Python2204',
        'address': '15教',
        'lecturer': {'name': 'lecturer', 'age': 18, 'qq': '222222', 'gender': '女'},
        'class_teacher': {'name': 'class_teacher', 'tel': '22223333'},
        'students': [
            {'name': 'stu1', 'age': 21, 'major': '会计', 'tel': '120', 'contacts': {'name': '张三', 'tel': '162723'}},
            {'name': 'stu2', 'age': 30, 'major': '电子', 'tel': '219223', 'contacts': {'name': '小明', 'tel': '281912'}},
            {'name': 'stu3', 'age': 19, 'major': '旅游管理', 'tel': '123233', 'contacts': {'name': '小花', 'tel': '886552'}},
            {'name': 'stu4', 'age': 25, 'major': '通信', 'tel': '4444221', 'contacts': {'name': '李四', 'tel': '22342345'}},
            {'name': 'stu5', 'age': 25, 'major': '机械', 'tel': '223111', 'contacts': {'name': '王五', 'tel': '555632'}},
            {'name': 'stu6', 'age': 23, 'major': '数学', 'tel': '234234', 'contacts': {'name': '赵六', 'tel': '96533'}}
        ]
    }
    
  4. 已知一个列表保存了多个狗对应的字典:

    dogs = [
      {'name': '贝贝', 'color': '白色', 'breed': '银狐', 'age': 3, 'gender': '母'},
      {'name': '花花', 'color': '灰色', 'breed': '法斗', 'age': 2},
      {'name': '财财', 'color': '黑色', 'breed': '土狗', 'age': 5, 'gender': '公'},
      {'name': '包子', 'color': '黄色', 'breed': '哈士奇', 'age': 1},
      {'name': '可乐', 'color': '白色', 'breed': '银狐', 'age': 2},
      {'name': '旺财', 'color': '黄色', 'breed': '土狗', 'age': 2, 'gender': '母'}
    ]
    
    1. 利用列表推导式获取所有狗的品种

      [‘银狐’, ‘法斗’, ‘土狗’, ‘哈士奇’, ‘银狐’, ‘土狗’]

      result = [x['breed'] for x in dogs]
      print(result)
      
    2. 利用列表推导式获取所有白色狗的名字

      [‘贝贝’, ‘可乐’]

      result = [x['name'] for x in dogs if x['color'] == '白色']
      print(result)
      
    3. 给dogs中没有性别的狗添加性别为 ‘公’

      for x in dogs:
          s.setdefault('gender', '公')
      print(dogs)
      
    4. 统计 ‘银狐’ 的数量

      count = 0
      for x in dogs:
          if x['breed'] == '银狐':
              count += 1
      print(count)        
      

列表

1. 基础题

  1. 已知一个数字列表,打印列表中所有的奇数

    a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    b = []
    for i in a:
        if i % 2 != 0:
            b.append(i)
    print(b)
    
  2. 已知一个数字列表,打印列表中所有能被能被3整除但是不能被2整除的数

    a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    b = []
    for i in a:
        if i % 2 != 0 and i % 3 == 0:
            b.append(i)
    print(b)
    
  3. 已知一个数字列表,计算所有偶数的和

    a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    b = []
    for i in a:
        if i % 2 == 0:
            b.append(i)
    print(sum(b))
    
  4. 已知一个数字列表,统计列表中十位数是1的数的个数

    a = [10, 12, 14, 34, 45, 67, 89]
    count = 0
    for i in a:
        if i // 10 == 1:
            count += 1
    print(count)
    
  5. 已知一个列表,获取列表中下标为奇数是所有元素(从0开始的下标值)

    例如: list1 = [10, 20, 5, 34, 90, 8]

    结果:[20, 34, 8]

    list1 = [10, 20, 5, 34, 90, 8]
    list2 = []
    for i in range(1, len(list1), 2):
        list2.append(list1[i])
    print(list2)
    
  6. 已知一个数字列表,将列表中所有元素乘以2

    例如: nums = [10, 3, 6, 12] 乘2后: nums = [20, 6, 12, 24]

    nums = [10, 3, 6, 12]
    for i in range(len(nums)):
        nums[i] *= 2
    print(nums)
    
  7. 已知一个列表,获取列表的中心元素

    例如:nums = [10, 2, 6, 12] -> 中心元素为: 2和6

    ​ nums = [10, 2, 6, 12, 10] -> 中心元素为:

    nums = [10, 2, 10, 6, 12]
    if len(nums) % 2 == 0:
        print(nums[len(nums) // 2], nums[len(nums) // 2 - 1])
    else:
        print(nums[len(nums) // 2])
    
  8. 已知一个列表,获取列表中所有的整型元素

    例如:list1 = [10, 1.23, ‘abc’, True, 100, ‘hello’, ‘20’, 5]

    ​ 结果是: [10, 100, 5]

    list1 = [10, 1.23, 'abc', True, 100,  'hello', '20', 5]
    list2 = []
    for i in list1:
        if type(i) == int:
            list2.append(i)
    print(list2)
    

2. 进阶题

  1. 定义一个列表保存多个学生的分数,删除列表中所以低于60分的值

    例如: scores = [45, 60, 89, 30, 12, 59, 99, 80, 71, 66] 删除后: scores = [60, 89, 99, 80, 71, 66]

    scores = [45, 60, 89, 30, 12, 59, 99, 80, 71, 66]
    new_scores=[]
    for i in scores:
        if i >= 60:
            new_scores.append(i)
    print(new_scores)
    
  2. 已知一个列表保存了多个学生的姓名,要求去掉列表中重复的名字

    例如:names = [‘小明’, ‘张三’, ‘李四’, ‘张三’, ‘张三’, ‘小明’, ‘王五’, ‘王五’]

    ​ 去重后:names = [‘小明’, ‘张三’, ‘李四’, ‘王五’]

    names = ['小明', '张三', '李四', '张三', '张三', '小明', '王五', '王五']
    names2=[]
    for i  in names:
        if i  not in names2:
            names2.append(i)
    print(names2)
    
  3. 已知一个数字列表,获取列表中值最大的元素 (不能使用max函数)

    list1 = [45, 60, 89, 30, 12, 59, 99, 80, 71, 66]
    list2 = 0
    for i in list1:
        if list2 <= i:
            list2 = i
    print(list2)
    
  4. 已知两个有序列表(列表中的元素已经按照从小到大的方式排好序),要求合并两个列表,合并后元素还是从小到大排序

    例如: list1 = [10, 23, 39, 41, 52, 55, 80] list2 = [9, 38, 55, 70]

    合并后的结果: [9, 10, 23, 38, 39, 41, 52, 55, 55, 70, 80]

    list1 = [10, 23, 39, 41, 52, 55, 80]
    list2 = [9, 38, 55, 70]
    list3 = list1 + list2
    print(list3)
    list3.sort()
    
  5. 已知一个有序数字列表(从小到大),输入任意一个数字,将输入的数字插入列表中,要求插入后列表仍然保持从小到大排序的关系

    例如: list1 = [10, 23, 45, 67, 91] 输入: 50 -> list1 = [10, 23, 45, 50, 67, 91]

    list1 = [10, 23, 45, 67, 91]
    number = int(input())
    list1.append(number)
    list1.sort()
    print(list1)
    

3. 列表推导式

  1. 创建一个列表,列表中有10个数字, 保证列表中元素的顺序,对列表进行排重,并对列表使用进行降序排序

    例如:[70, 88, 91, 70, 107, 234, 91, 177, 282, 197]
    		--- 去重之后 [70, 88, 91, 107, 234, 177, 282, 197]
      	---- 降序排序 [282, 234, 197, 177, 107, 91, 88, 70]
    
    >>> a = [70, 88, 91, 70, 107, 234, 91, 177, 282, 197]
    >>> b = []
    >>> for i in a:
    ...     if i not in b:
    ...         b.append(i)
    ...
    >>> b
    [70, 88, 91, 107, 234, 177, 282, 197]
    >>> b.sort(reverse=True)
    >>> b
    [282, 234, 197, 177, 107, 91, 88, 70]
    
  2. 利用列表推导式, 完成以下需求

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

    结果为 [3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
    
    >>> a = [i for i in range(3, 100, 10)]
    >>> a
    [3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
    

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

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

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

    例如: ["good", "nice", "see you", "bye"] --- [4, 4, 7, 3]
    
    >>> a = [len(i) for i in ["good", "nice", "see you", "bye"]]
    >>> a
    [4, 4, 7, 3]
    

    d. 利用列表推导式删除列表中整数个位数小于5的元素

    例如:[24, 'abc', 99, True, 21, 38, 'hello'] --- ['abc', 99, True, 38, 'hello']
    
    >>> a = [i for i in [24, 'abc', 99, True, 21, 38, 'hello'] if type(i)== int and i % 10 >= 5 or type(i) != int]
    >>> a
    ['abc', 99, True, 38, 'hello']
    

    e. 利用列表推导式获取元素是元组的列表中每个元组的最后一个元素

    例如:[(10, 20, 30), ('abc', 'hello'), (1, 2, 3.4), (True, False)]  --- [30, 'hello', 3.4, False]
    
    >>> a = [[(10, 20, 30), ('abc', 'hello'), (1, 2, 3.4), (True, False)][i][-1] for i in range(4)]
    >>> a
    [30, 'hello', 3.4, False]
    

    f.利用列表推导式将数字列表中所有的奇数乘以2,所有的偶数除以2

    例如: [23, 4, 67, 88, 90, 21]  -> [46, 2, 134, 44, 45, 42]
    
    >>> a = [i * 2 if i % 2 != 0 else (i // 2) for i in [23, 4, 67, 88, 90, 21]]
    >>> a
    [46, 2, 134, 44, 45, 42]
    
  3. 已知一个列表获取列表中指定元素所有的下标

    例如:[10, 20, 34, 10, 9, 78]
    10的下标:[0, 3]
    20的下标:[1]
    30的下标:[]
    
    a = [10, 20, 34, 10, 9, 78]
    b = int(input())
    c = []
    for i in range(len(a)):
        if b == a[i]:
            c.append(i)
    print(f'{b}的下标:{c}')
    c.clear()
    
    运行结果:
    >? 10
    10的下标:[0, 3]
    >? 20
    20的下标:[1]
    >? 30
    30的下标:[]
    
  4. *已知一个数字列表,写程序判断这个列表时候是连续递增列表。

    例如:
    [1, 2, 3, 4, 5]   -> True
    [23, 45, 78, 90]  -> True
    [1, 3, 2, 4, 5]	-> False
    
    >>> a = [1, 2, 3, 4, 5]
    >>> b = []
    >>> for i in a:
    ...     b.append(i)
    ...
    >>> a.sort()
    >>> if b == a:
    ...     print('True')
    ... else:
    ...     print('False')
    ...
    True
    
  5. 已知两个列表,将两个列表按照下面的规律交叉合并

    A = [10, 20, 30, 40, 50]
    B = [100, 200, 300]
    结果:[10, 100, 20, 200, 30, 300, 40, 50]
    
    >>> A = [10, 20, 30, 40, 50]
    >>> B = [100, 200, 300]
    >>> c = []
    >>> for i in range(len(B)):
    ...     c.append(A[i])
    ...     c.append(B[i])
    ...
    >>> for i in A:
    ...     if i not in c:
    ...         c.append(i)
    ...
    >>> c
    [10, 100, 20, 200, 30, 300, 40, 50]
    
  6. 已知两个有序列表,将两个列表合并,合并后的新列表中元素仍然是递增列表

    A = [10, 20, 30, 40, 50]
    B = [25, 44, 60]
    结果:[10, 20, 25, 30, 40, 45, 50, 60]
    
    >>> A = [10, 20, 30, 40, 50]
    >>> B = [25, 44, 60]
    >>> C = A + B
    >>> C.sort()
    >>> C
    [10, 20, 25, 30, 40, 44, 50, 60]
    

第二周作业

选择题

  1. 下列选项中能正确表示一个列表的是(D)。

    A. {1, 2, 3}

    B. [10, abc, 123]

    C. [10 20 30]

    D. [1, 2, 3]

    b, c错误输入,a为集合
    
    >>> a = {1, 2, 3}
    >>> b = [10, abc, 123]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'abc' is not defined
    >>> c = [10 20 30]
      File "<stdin>", line 1
        c = [10 20 30]
                ^
    SyntaxError: invalid syntax
    >>> d = [1, 2, 3]
    >>> type(a)
    <class 'set'>
    >>> type(d)
    <class 'list'>
    
  2. (多选)已知一个列表nums = [10, 20, '小明', [1, 2]],以下表达式结果是小明的是?(CD)

    A. nums[-3]
    结果为20

    B. nums[3]
    结果为[1, 2]

    C. nums[-2]

    D. nums[2]

  3. 以下选项关于列表说法错误的是?(C)

    A. 列表可以放在for循环的in后面

    B. 列表是可变的序列

    C. 列表是有序的,只支持增删改,不支持查操作

    D. 列表的in操作可以判断元素是否存在

  4. 已知一个列表names = ['小乔', '甄姬', '王昭君', '妲己', '女娲', '西施', '嬴政'],下面的表达式中结果是[]的是?(C)

    A. names[1:]

    B. names[:1]

    C. names[1:4:-1]

    D. names[1:4:2]

  5. 已知列表list1 = [10, [1, 2], 100, 1000],下列表达式结果是True的是?(D)

    A. 100 not in list1

    B. 1 in list1

    C. 2 in list1

    D. [1, 2] in list1

  6. 下列选项中不属于序列的是?(D)

    A. []

    B. '100'

    C. {1, 2}

    D. 100

    A为列表,B为字符串,C为集合,ABC都可以用for i in ...这种形式进行遍历,说明为序列。
    
  7. 已知student = {'name': '小明', 'age': 18, 'gender':'男'}下列关于字典的操作正确的是?(D)

    A. student('name')

    B. student[name]

    C. student['小明']

    D. student['age']

  8. 下列表达式有误的是?(D)

    A. 100 + 30.03

    B. 188 * '12'

    C. 188 * 12

    D. 188 + '12'

    >>> 188 + '12'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    >>>整型和字符串不能相加
    
  9. (多选)下列表达式能产生[1, 2, 3]的是?(ABD)

    A. [1, 2] + [3]

    B. [1, 2].append(3)

    C. [1, 2].extend(3)

    D. [1, 2, 3] * 1

    >>> [1, 2].extend(3)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not iterable
    类型错误:'int'对象不是可迭代对象    
    
    可以这样添加
    >>> a
    [1, 2, 3]
    >>> a.extend([4, 5])
    >>> a
    [1, 2, 3, 4, 5]
    
  10. (多选)下列选项中属于可变序列的是?(AC)

    A. 列表

    B. 元组

    C. 字典

    D. 字符串

填空题

  1. python中获取指定数据的类型可以使用( type )函数。
  2. 查看数据地址的函数是( id )。
  3. 如果要将数据转换成列表,需要使用( list() )。
  4. ( len() )函数可以用来获取任意序列中元素的个数。
  5. 如果需要将一个数据插入到列表的中间需要使用函数( insert )。
  6. Python中数学集合运算中求交集、并集、差集和对称差集的符号分别是( & )、( | )、( - )、( ^ )。
  7. 请列举出你知道的Python中的不可变的数据类型:( str、 tuple、 int )。
  8. 获取字符编码值和获取编码值对应的字符的函数分别是( ord )、( chr )。
  9. 如果要判断序列中是否存在某个元素可以使用( in )来判断。
  10. 如果要判断两个数据的地址是否相等可以使用( is )。

编程题

  1. 已知一个列表names = ['胡歌', '王凯', '王俊凯', '杨幂', '刘德华', '张国荣', '王祖贤', '张伟']

    1)依次打印列表中的每个元素

    2)统计列表中姓的人的个数。

    3)统计名字是两个字的人的个数。

    >>> names = ['胡歌', '王凯', '王俊凯', '杨幂', '刘德华', '张国荣', '王祖贤', '张伟']
    >>> for i in names:
    ...     print(i)
    ...
    胡歌
    王凯
    王俊凯
    杨幂
    刘德华
    张国荣
    王祖贤
    张伟
    >>> count = 0
    >>> for i in names:
    ...     if i[0] == '张':
    ...             count += 1
    ...
    >>> count
    2
    >>> count = 0
    >>> for i in names:
    ...     if len(i) == 2:
    ...             count += 1
    ...
    >>> count
    4
    
  2. 已知字典dog = {'name': '大黄', 'color': 'yellow', 'age': 3, 'kind': '土狗'}

    1)打印所有key对应的值

    2)将name的值修改成 ‘旺财’

    3)添加狗的价格对应的键值对

    4)清空dog字典

    >>> dog = {'name': '大黄', 'color': 'yellow', 'age': 3, 'kind': '土狗'}
    >>> for i in dog.values():
    ...     print(i)
    ...
    大黄
    yellow
    3
    土狗
    >>> dog['name'] =  '旺财'
    >>> dog
    {'name': '旺财', 'color': 'yellow', 'age': 3, 'kind': '土狗'}
    >>> dog['price'] = 1000
    >>> dog
    {'name': '旺财', 'color': 'yellow', 'age': 3, 'kind': '土狗', 'price': 1000}
    >>> dog.clear()
    >>> dog
    {}
    
  3. 已知字符串message = 'You see see, one day day!'

    1)统计字符串中非字母的字符个数

    2)提取出所有的小写字母

    >>> message = 'You see see, one day day!'
    >>> count = 0
    >>> for i in message:
    ...     if not ("a" <= i <= "z" or "A" <= i <= "Z"):
    ...             count += 1
    ...
    >>> count
    7
    >>> count = 0
    >>> for i in message:
    ...     if i.islower():
    ...             count += 1
    ...
    >>> count
    17
    >>> len(message)
    25    # 25 = 1大写 + 17小写 + 7非字母
    

    补充

    # s 代表字符串
    s.isalnum() 	#所有字符都是数字或者字母
    s.isalpha() 	#所有字符都是字母
    s.isdigit() 	#所有字符都是数字
    s.islower() 	#所有字符都是小写
    s.isupper() 	#所有字符都是大写
    s.istitle() 	#所有单词都是首字母大写,像标题
    s.isspace() 	#所有字符都是空白字符、\t、\n
    
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 列表Python中最常用的数据类型之一,它可以存储多个元素,这些元素可以是不同的数据类型,如整数、浮点数、字符串等。列表使用方括号 [] 来表示,元素之间用逗号隔开。 例如,下面是一个包含整数、浮点数和字符串列表: ``` my_list = [1, 2.5, "hello"] ``` 列表中的元素可以通过索引访问,索引从开始,例如: ``` print(my_list[]) # 输出 1 print(my_list[2]) # 输出 "hello" ``` 列表还支持切片操作,可以通过切片获取列表的子集,例如: ``` print(my_list[1:]) # 输出 [2.5, "hello"] ``` 列表是可变的,可以通过索引或切片修改列表中的元素,也可以使用 append() 方法向列表末尾添加新元素,例如: ``` my_list[] = 3 my_list.append("world") print(my_list) # 输出 [3, 2.5, "hello", "world"] ``` 除了 append() 方法,列表还支持 insert()、remove()、pop() 等方法,可以对列表进行增删改查操作。 ### 回答2: Python中的列表是一种非常常用的数据结构,是一组有序的元素集合,可以通过索引来访问其中的元素。列表可以包含多种类型的数据,包括数字字符串列表等等,且可以根据需要动态地添加、删除、修改其中的元素。在Python中,列表的创建方式非常简单,只需要用一组方括号将其中的元素括起来即可。 可以使用列表的索引来获取其中的元素。在Python中,列表的索引从0开始,即第一个元素的索引为0,第二个元素的索引为1,以此类推。要访问列表中的最后一个元素,可以使用-1作为索引,-2表示倒数第二个元素,依此类推。 列表元素的访问、添加、删除、修改、排序等操作属于Python基础知识,这里简单介绍其中几个: 1.访问列表元素:可以使用索引号来访问列表元素。例如,list=[1,2,3],要访问第一个元素,可以使用list[0],输出为1。 2.添加元素:可以使用append()方法向列表中添加一个元素,或者使用extend()方法向列表中添加多个元素。例如,list=[1,2,3],要添加一个元素4,可以使用list.append(4);要添加多个元素5,6,7,可以使用list.extend([5,6,7])。 3.删除元素:可以使用del语句或者remove()方法来删除列表中的元素。del语句直接删除列表中指定索引的元素,例如,del list[0]可以删除列表第一个元素;remove()方法删除第一个匹配的元素,例如,list.remove(2)可以删除列表中的元素2。 4.修改元素:可以使用索引号来修改列表中的元素,例如,list[1]=5可以将列表中第二个元素修改为5。 5.排序:可以使用sort()方法对列表进行排序,默认是升序排列,也可以指定reverse=True来进行降序排列。 以上是Python列表的基本操作,熟练掌握这些操作,可以更好地使用列表进行各种计算和数据处理。 ### 回答3: 在Python中,列表(List)是一种非常常用的数据类型,它允许我们将一组数据放在一个容器中,方便进行操作和处理。列表可以在定义时直接初始化,也可以通过append()、insert()等方法动态地添加或删除元素。 列表的索引从0开始,可以通过正、负整数来访问其中的元素。同时,列表支持切片操作,可以对其中的子序列进行访问和操作。 除了常规的访问和添加操作,列表还提供了一些其他的方法,例如sort()可以对列表进行排序,reverse()可以将列表翻转,count()可以统计某个元素的出现次数等等。 另外,列表还支持循环遍历,可以使用for-in语句来遍历其中的元素。此外,列表也可以被用作其他数据结构的实现,例如栈、队列等等。 总的来说,列表Python中一个非常灵活和强大的数据类型,可以用于各种场景下的数据处理和操作。但是需要注意,由于列表是可变的,因此在多线程、多进程等并发环境中需要考虑线程安全的问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值