Python——列表的增删改查
作者:互联网
#定义初始列表
name_list = ["zhangsan", "lisi", "wangwu"]
查找
print(name_list[2])
print(name_list.index("wangwu"))
wangwu
2
修改
name_list[1] = "李四"
print(name_list)
[‘zhangsan’, ‘李四’, ‘wangwu’]
增加
#append方法可以向列表的末尾追加数据
name_list.append("唐僧")
print(name_list)
[‘zhangsan’, ‘李四’, ‘wangwu’, ‘唐僧’]
#insert方法可以在列表的指定索引位置插入数据
name_list.insert(1, "aaa")
print(name_list)
[‘zhangsan’, ‘aaa’, ‘李四’, ‘wangwu’, ‘唐僧’]
#extend可以把其他列表中的完整内容,追加到当前列表末尾
temp_list = ["孙悟空", "猪八戒", "沙和尚"]
name_list.extend(temp_list)
print(name_list)
[‘zhangsan’, ‘aaa’, ‘李四’, ‘wangwu’, ‘唐僧’, ‘孙悟空’, ‘猪八戒’, ‘沙和尚’]
删除
#remove方法可以从列表中删除指定的数据
name_list.remove("wangwu")
print(name_list)
[‘zhangsan’, ‘aaa’, ‘李四’, ‘唐僧’, ‘孙悟空’, ‘猪八戒’, ‘沙和尚’]
#pop方法默认删除列表最后一个数据
name_list.pop()
print(name_list)
[‘zhangsan’, ‘aaa’, ‘李四’, ‘唐僧’, ‘孙悟空’, ‘猪八戒’]
#pop方法可以指定要删除元素的索引
name_list.pop(3)
print(name_list)
[‘zhangsan’, ‘aaa’, ‘李四’, ‘孙悟空’, ‘猪八戒’]
#clear方法可以清空列表
name_list.clear()
print(name_list)
[]
标签:name,Python,改查,list,wangwu,print,李四,增删,zhangsan 来源: https://blog.csdn.net/weixin_45646929/article/details/120239147