python列表删除元素

简介: python列表删除元素

列表直接删除元素


方法一: remove: 删除单个元素,删除首个符合条件的元素,按值删除


str = [1,2,3,4,3,5,6,2]
 str.remove(3)
 print(str)  # [1, 2, 4, 3, 5, 6, 2]


方法二: pop: 删除单个或多个元素,按位删除(根据索引删除), 删除时会返回被删除的元素


str_pop= [1,2,3,4,3,5,6,2]
 str_pop.pop(3)
 print(str_pop)  # [1, 2, 3, 3, 5, 6, 2]


方法三: del: 根据索引删除


str_del= [1,2,3,4,3,5,6,2]
 del str_del[1]
 print(str_del)  # [1, 3, 4, 3, 5, 6, 2]


列表遍历过程中删除元素, 会造成不可预知错误, 可使用下面几种方法删除


方法一: 列表推导式

# 删除 <4
 list1 = [1, 2, 3, 4, 5, 6]
 new_list1 = [i for i in list1 if i > 4]
 print(new_list1)


方法二: filter + lambda


# 删除 <4
 list2 = [1, 2, 3, 4, 5, 6]
 new_list2 = filter(lambda i: i > 4, list2)
 print(list(new_list2))


方法三: 倒序遍历


# 删除 >4
list3 = [1, 2, 3, 4, 5, 6]
for i in range(len(list3)-1, -1, -1):
    if list3[i] > 4:
        list3.remove(list3[i])
print(list3)


方法四:


# 删除 >4
 list4 = [1, 2, 3, 4, 5, 6]
 new_list4 = []
 for i in list4:
     if i <= 4:
         new_list4.append(i)
 print(new_list4)


目录
相关文章
|
1月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
163 1
|
1月前
|
开发者 Python
Python列表推导式:优雅与效率的完美结合
Python列表推导式:优雅与效率的完美结合
371 116
|
1月前
|
Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
373 119
|
2月前
|
缓存 监控 数据可视化
微店item_search - 根据关键词取商品列表深度分析及 Python 实现
微店item_search接口可根据关键词搜索商品,返回商品信息、价格、销量等数据,适用于电商检索、竞品分析及市场调研。接口需通过appkey与access_token认证,支持分页与排序功能,Python示例代码实现调用流程,助力商品数据高效获取与分析。
|
1月前
|
开发者 Python
Python列表推导式:优雅与效率的完美融合
Python列表推导式:优雅与效率的完美融合
319 104
|
1月前
|
Python
Python列表推导式:优雅与效率的艺术
Python列表推导式:优雅与效率的艺术
245 99
|
1月前
|
数据处理 Python
解锁Python列表推导式:优雅与效率的完美融合
解锁Python列表推导式:优雅与效率的完美融合
262 99
|
1月前
|
开发者 Python
Python列表推导式:一行代码的艺术与力量
Python列表推导式:一行代码的艺术与力量
358 95
|
2月前
|
开发者 Python
Python神技:用列表推导式让你的代码更优雅
Python神技:用列表推导式让你的代码更优雅
428 99
|
2月前
|
程序员 Python
Python列表推导式:简洁与高效的艺术
Python列表推导式:简洁与高效的艺术
272 99

推荐镜像

更多