龙空技术网

python中列表的增删查改

修道小鱼 228

前言:

如今你们对“python 修改列表中的某个值”都比较讲究,咱们都想要学习一些“python 修改列表中的某个值”的相关文章。那么小编同时在网络上搜集了一些有关“python 修改列表中的某个值””的相关资讯,希望各位老铁们能喜欢,你们一起来学习一下吧!

列表:

list = ["apple","Banana","orange","grape"]

1、添加数据方法:

方法一:append(往列表的结尾处添加一个元素)

示例:

list = ["apple","Banana","orange","grape"]

list.append("mango")

print(list)

方法二:insert(往列表中指定索引位置插入元素)

示例:

list = ["apple","Banana","orange","grape"]

list.insert(0,"mango")

print(list)

特别注意:(插入数据如果用的是反向索引,会先转换为正向索引再进行数据插入)

示例:

list = ["apple","Banana","orange","grape"]

list.insert(-1,"mango")

print(list)

特别提示:(插入数据用的索引超出列表的索引范围,会默认插入到最后一个)

示例:

list = ["apple","Banana","orange","grape"]

list.insert(10,"mango")

print(list)

方法三:extend(一次性往列表尾部插入多个元素)

extend方法传列表:

示例:

list = ["apple","Banana","orange","grape"]

list.extend(["pitaya","mango"])

print(list)

extend方法传字符串:(会把字符串中的每一个字符当做一个元素插入到列表)

示例:

list = ["apple","Banana","orange","grape"]

list.extend("abcd")

print(list)

2、删除数据方法:

list = ["apple","Banana","orange","grape","pitaya","mango"]

方法一:remove:指定元素进行删除(若列表中存在多个相同的元素,只会删除找到的第一个元素)

示例:

list = ["apple","Banana","orange","grape","pitaya","mango","apple","Banana"]

list.remove("apple")

print(list)

方法二:pop:指定索引进行删除(如果不指定位置,默认删除列表最后一个元素)

示例:

list = ["apple","Banana","orange","grape","pitaya","mango","apple","Banana"]

list.pop()

print(list)

备注:pop方法调用完,会返回生产的数据。

示例:

list = ["apple","Banana","orange","grape","pitaya","mango","apple","Banana"]

list1 = list.pop(0)

print(list)

print(list1)

方法三:clear(清空列表中的所有元素)

示例:

list = ["apple","Banana","orange","grape","pitaya","mango","apple","Banana"]

list.clear()

print(list)

3、修改列表中元素的值:

通过索引字指定位置进行修改

示例:

list = ["apple","Banana","orange","grape"]

list[2] = "mango"

print(list)

4、查找列表中的元素:

索引取值:

示例:

list = ["apple","Banana","orange","grape"]

list1 = list[2]

print(list1)

查询列表中元素对应的索引:

方法一:index(查找的元素在列表中不存在时,会抛异常)

示例1:

list = ["apple","Banana","orange","grape"]

list1 = list.index("orange")

print(list1)

示例2:

list = ["apple","Banana","orange","grape"]

list1 = list.index("mango")

print(list1)

方法二:count统计列表中某一个元素的个数

示例:

list = ["apple","Banana","apple","orange","apple","grape","apple"]

res = list.count("apple")

print(res)

特别提示:如何识别使用方法后要不要用变量接收返回数据,按住【CTRL】键,鼠标光标移动到方法名上边,提示弹窗方法名后的>符号显示的是None,就不需要变量接收数据。

标签: #python 修改列表中的某个值