当前位置: 代码迷 >> 综合 >> python列表的基本操作
  详细解决方案

python列表的基本操作

热度:6   发布时间:2024-01-17 15:31:23.0


列表的基本操作


获取列表的一些基本信息

    list1 = [9, 1, -4, 3, 7, 11, 3]# print('list1的长度=', )print('list1的长度=', len(list1))                  # list1的长度= 7# print('list1里的最大值=', )print('list1里的最大值=', max(list1))              # list1里的最大值= 11# print('list1里的最小值=',min(list1))print('list1里的最小值=', min(list1))              # list1里的最小值= -4# print('list1里3这个元素一共出现了{}次'.format())print('list1里3这个元素一共出现了{}次'.format(list1.count(3)))# list1里3这个元素一共出现了2次


列表的改变

    list2 = ['a', 'c', 'd']# 给list2结尾添加一个新元素 'e'list2.append('e')print(list2)                            # ['a', 'c', 'd', 'e']# 在list2的'a'和'c'之间插入一个 'b'list2.insert(1, 'b')                    # def insert(self, index, p_object)print(list2)                            # index:代表要在什么位置插入# ['a', 'b', 'c', 'd', 'e']# 删除list2里的'b'list2.remove('b')                       # def remove(self, value)print('list2=', list2)                  # list2= ['a', 'c', 'd', 'e']# 或者可以通过索引来更改,但是如果list2中有字符串,则不能通过该方法给字符串赋值list2[0] = '1'print('list2=', list2)                  # list2= ['1', 'c', 'd', 'e']# 列表翻转list3 = [1, 2, 3]list3.reverse()print('list2=', list3)                  # list2= [3, 2, 1]# 列表排序list4 = [9, 1, -4, 3, 7, 11, 3]list4.sort()                            # 正序排序print('list4=', list4)                  # list4= [-4, 1, 3, 3, 7, 9, 11]list4.sort(reverse=True)                # 倒序排序print('list4=', list4)                  # list4= [11, 9, 7, 3, 3, 1, -4]

 

  相关解决方案