python中list常见的"增 删 改 查"

列表的增删改查

name_list = ["张三", "李四", "王五"]

1、查看name_list的索引为1的元素

print("1、name_list索引为1的元素是:%s" % name_list[1])

2、查看王五在name_list的索引位置

print("2、name_list中元素\"王五\"的索引是:%d" % name_list.index("王五"))

3,在name_list中增加唐僧,孙悟空,猪八戒、沙悟净,敖烈元素
name_list.append(“唐僧”)

print("3.1、通过append增加元素后的新列表是%s" % name_list)
name_list.insert(5, "孙悟空")
print("3.2、通过insert增加元素后的新列表是%s" % name_list)

总结,通过insert添加元素时,必须指定索引

name_list.insert(2, "沙悟净")
print("3.3、通过insert追加元素时,如果指定索引已存在,则在新的列表中起到修改作用,例子%s" % name_list)
hothous = ["贾宝玉", "薛宝钗", "薛仁贵"]
name_list.extend(hothous)
print("3.4、通过extend追加到新列表中,extend只能将列表进行追加,举例,%s为待合并列表,%s为合并后的列表" % (hothous, name_list))

4、列表的删

name_list.pop()
print("4.1、方法pop默认删除最后一个元素,默认参数的新列表为:%s" % name_list)
name_list.pop(3)
print("4.2、方法pop指定索引之后生成的新列表为 %s" % name_list)
del name_list[0]
print("4.3、\"del\"删除列表的元素,需要指定索引,是从物理内存中删除,删除后的新列表为: %s" % name_list)

name_list.clear()

# print("4.4\"clear \"是清空整个列表,%s" % name_list)

5、列表的改

name_list[0] = "西游记"
print("5.1、通过对应索引进行修改,原列表中索引为0的元素为\"张三\",修改之后为%s" % name_list)
name_list.insert(0, "红楼梦")
print("5.2、详见增加方法3.3%s" % name_list)

6、列表的查看
查看索引为0的元素是?

print("6.1、查看索引为0的元素是:\"%s\"" % name_list[0])
print("通过索引查看元素的升级代码:%s" % name_list[int(input("6.2、请输入您要选择查看的索引"))])
print("6.3、通过方法.index查看元素对应的索引\"%d\"" % name_list.index("红楼梦"))
 print("升级版本:通过方法.index查看元素对应的索引\"%d\"" % name_list.index(input("6.3、请输入您要查询的元素")))

7、列表的遍历

for suoyin in name_list:
    print(suoyin)

以上是通过for in 进行的遍历 还可以通过while循环进行遍历

print("~" * 50)
i = 0
while i < len(name_list):
    print("索引%d对应的元素为%s" % (i, name_list[i]))
    i += 1

8、 查看列表的长度 主要是通过len函数进行操作

len(name_list)

ps:列表中除了可以容纳str外,还可以储存字典、元祖等

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值