Problem
有一个list()对象包含若干个元素,我们想对其中的内容做一些操作,不满足条件的元素要被remove()出去,eg.
for i in List_l:
if 't' in i:
List_l.remove(i)
我们会自然的写出这样的代码,问题出在当遍历时 “i” 的次序就已经确定好了,删除操作出现时整个列表就会往前移动,所以就不会得到想要的效果。
Solution
- copy出一个新的列表用来做遍历,原来的列表进行删除操作
- 内建函数filter()
sl = filter(lambda x: 't' not in x, sl)
- 列表解析
a = [1,2,3,4,5,6,7,8]
b = [i for i in a if i >5]
print(b)
- 倒序删除
for i in range(len(a)-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