栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python

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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/961007.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号