Python_List remove()方法

Problem

有一个list()对象包含若干个元素,我们想对其中的内容做一些操作,不满足条件的元素要被remove()出去,eg.

for i in List_l:
	if 't' in i:
		List_l.remove(i)

我们会自然的写出这样的代码,问题出在当遍历时 “i” 的次序就已经确定好了,删除操作出现时整个列表就会往前移动,所以就不会得到想要的效果。

Solution

  1. copy出一个新的列表用来做遍历,原来的列表进行删除操作
  2. 内建函数filter()
sl = filter(lambda x: 't' not in x, sl)
  1. 列表解析
a = [1,2,3,4,5,6,7,8]
b = [i for i in a if i >5]
print(b)
  1. 倒序删除
for i in range(len(a)-1,-1,-1):
  1. while循环

tips

要删除(和)中的所有文本,可以使用re中的findall()方法并使用replace()删除它们:

import re
test_string = 'This is a string (here is a text to remove), and here is a (second one) text not to remove'
remove = re.findall(r" \(.*?\)",test_string)
for r in remove:
    test_string = test_string.replace(r,'')
print(test_string)
#result: This is a string , and here is a  text not to remove
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Loganer

感谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值