Python基础之列表及元组的增删改查

定义一个列表

晚上的状态不太适合写博客,容易犯困~

  • 列表的增加有三种方式

    • 第一种主流的增加 append函数
    list1 = ['noevil', 'fordearme', 'city', 'custom']
    # 列表的增加 append
    list1.append('你好')
    print(list1) # ['noevil', 'fordearme', 'city', 'custom', '你好']
    
    # 如果输入为q就退出,否则输入的员工名字将持续添加
    person_list = []
    while 1:
        add_person = input('请输入要添加的员工名字: ')
        # 不区分大小写
        if add_person.strip().upper() == 'Q':
            break
        person_list.append(add_person)
    print('公司现有人员名单%s' % person_list)
    
    • 第二种 insert函数 L.insert(插入的索引位置, 插入的对象)
    list1 = ['noevil', 'fordearme', 'city', 'custom']
    list1.insert(0, 'no give')
    ['no give', 'noevil', 'fordearme', 'city', 'custom']
    list1.insert(4, 'no give')
    ['noevil', 'fordearme', 'city', 'custom', 'no give']
    
    • 第三种 列表的迭代添加
    list1.extend('二哥')
    print(list1) 
    ['noevil', 'fordearme', 'city', 'custom', '二', '哥']
    列表的迭代添加的对象必须是可迭代对象,int不是
    list1.extend(123)
    print(list1)
    

    报错信息如下:

报错信息

正确添加方式如下:

    list1.extend([1, 2, 3])
    print(list1)
    ['noevil', 'fordearme', 'city', 'custom', '二', '哥', 1, 2, 3]

列表的删除

  • 按照索引删除 pop函数

    li = ['youxiu', 'laogan', 'laosi', 'chenwei']
    del_li2 = li.pop()  # 如果不指定索引值,默认删除最后一个
    print(li)  # ['youxiu', 'laogan', 'laosi']
    del_li = li.pop(1) # 指定了删除索引为1的
    print(li) #['youxiu', 'laosi', 'chenwei']
    print(del_li)  # laogan 返回值为删除的对象
    
  • 按元素删除 remove函数

    li = ['男神', '女神', '丘比特']
    li.remove('男神')
    print(li)  # ['女神', '丘比特']
    
  • 一般不用的,全部删除,清空列表

    li.clear()
    print(li)  # []
    
  • 直接删除连列表

    del li
    
  • 切片删除

    del li[2:4]
    

列表的修改

test1 = ['徐鹏SB', '孙悟空', '八戒', '猕猴']
print(test1[0])  
# 徐鹏SB

# 原理是先把索引范围内的值给拿出来,之后循环的往里面添加你要修改的字符串或者列表等
test1[0:2] = '这个你会很吃惊'
print(test1)
# ['这', '个', '你', '会', '很', '吃', '惊', '八戒', '猕猴']

公共的方法

# 列表的统计指定字符出现次数
test2 = ['s', 's', 'c', 'dd', 'p']
total_count = test2.count('s')
print(total_count)

# 找指定字符第一次出现的索引,可以选择索引的 范围

index_str = test2.index('s', 1, 3)
print(index_str)  # 1

# 列表的排序
# 正向排序
sort_list = [5, 4, 2, 6, 8, 3]
# sort_list.sort()
# print(sort_list)
# [2, 3, 4, 5, 6, 8]

# 反向排序

# sort_list.sort(reverse=True)
# print(sort_list)
# [8, 6, 5, 4, 3, 2]

# 反转排序
sort_list.reverse()
print(sort_list)
# [3, 8, 6, 2, 4, 5]

元组

  • 只读文件,只能,不可修改,但是元组自身不可以修改,却可能可以修改自己的儿子
test_tuple = ('hello', 'world', [1, 2, 3, '就要改你'], 89)
# 可以查询
print(test_tuple[1])

gai

# 但是我们修改他自己
test_tuple[1] = '我改'
  • 结果会报错

gai

 # 元组里面的可变类型是可以修改的
test_tuple[2][3] = test_tuple[2][3] = '改了'
print(test_tuple)
  • 可以看见元组里面的列表已经修改,所以元组的不可更改并不是真正意义上的不可修改
    gai
li = [1, 2, 3, 5, 'jls', [2, 3, 4, 5, 'youxiu'], 'sff']
for i in li:
    if type(i) == list:
        for j in i:
            print(j)
    else:
        print(i)
  • 结果如下:

gai

有一个有意思的题目

for i in range(0, 10, -1):
   print(i)
# 输出结果是什么,肯定不是你想的那样

结果即不报错,也不输出什么:
gai

原文地址:https://www.cnblogs.com/lishi-jie/p/9853616.html