admin管理员组文章数量:1642512
python for 循环中使用 remove 删除列表中的元素
错误的代码
# !/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
old_list = [1, 1, 2, 3, 4, 1, 5, 6, 1, 7, 8]
for member in old_list:
if member == 1:
old_list.remove(member)
print(old_list)
原因
原因是不能在for循环中用remove同一个列表(遍历中删除)。当remove这个list中的元素时,list的长度发生了变化,for循环就会受到影响
解决办法:
用一个新的列表(list)去代替循环中的list或者代替remove操作的list。在创建新的列表是可以用cpoy模块中的deepcopy方法也可以用new_list = old_list[:]的方法:
正确的代码
# !/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
from copy import deepcopy
old_list = [1, 1, 2, 3, 4, 1, 5, 6, 1, 7, 8]
new_list = deepcopy(old_list)
for member in new_list:
if member == 1:
old_list.remove(member)
print(old_list)
版权声明:本文标题:python for 循环中使用 remove 删除列表中的元素 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1729340260a1197451.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论