Python 如何从列表中永久删除字符串?
脚本打印出我想要的列表。。。 但是如何让脚本将Python 如何从列表中永久删除字符串?,python,string,list,Python,String,List,脚本打印出我想要的列表。。。 但是如何让脚本将文件列表更改为: fileList=['b.pdf','d.pdf'] 我试过 fileList = ['a.txt', 'b.pdf','c.exe','d.pdf','e.mp3'] extension = '.pdf' for i in fileList: if extension in i: print i >>> b.pdf d.pdf >>> 接着是 for i in fil
文件列表更改为:
fileList=['b.pdf','d.pdf']
我试过
fileList = ['a.txt', 'b.pdf','c.exe','d.pdf','e.mp3']
extension = '.pdf'
for i in fileList:
if extension in i:
print i
>>>
b.pdf
d.pdf
>>>
接着是
for i in fileList:
if extension not in i:
但是文件列表
永远不会永久更改。您应该尝试迭代文件列表
的副本,并从文件列表
中删除。范例-
del i, fileList.pop, fileList.remove, etc
但实际上您并不需要这样做,您可以使用简单的列表理解,只需将名称fileList
指向没有扩展名的文件不存在的位置。另外,您可以使用string.endswith
检查字符串是否以值结尾
范例-
del i, fileList.pop, fileList.remove, etc
>>> fileList = ['a.txt', 'b.pdf','c.exe','d.pdf','e.mp3']
>>> extension = '.pdf'
>>>
>>> for i in fileList[:]:
... if not i.endswith(extension):
... fileList.remove(i)
...
>>> fileList
['b.pdf', 'd.pdf']
您应该尝试迭代文件列表
的副本,并从文件列表
中删除。范例-
del i, fileList.pop, fileList.remove, etc
但实际上您并不需要这样做,您可以使用简单的列表理解,只需将名称fileList
指向没有扩展名的文件不存在的位置。另外,您可以使用string.endswith
检查字符串是否以值结尾
范例-
del i, fileList.pop, fileList.remove, etc
>>> fileList = ['a.txt', 'b.pdf','c.exe','d.pdf','e.mp3']
>>> extension = '.pdf'
>>>
>>> for i in fileList[:]:
... if not i.endswith(extension):
... fileList.remove(i)
...
>>> fileList
['b.pdf', 'd.pdf']
试一试
试一试
某些列表操作不是很有效<代码>插入
和从随机位置删除
是一对O(n)型
从使用for
循环进行迭代的列表中删除项目也是引入错误的好方法,因为删除项目之后的项目将被跳过
事实证明,创建一个新列表过滤掉不需要的项目通常效率更高
del list[index]
#example :-
del list[1]
请注意,我将逻辑更改为使用
endswith
,以防止文件名路径中的意外匹配某些列表操作效率不高<代码>插入和从随机位置删除
是一对O(n)型
从使用for
循环进行迭代的列表中删除项目也是引入错误的好方法,因为删除项目之后的项目将被跳过
事实证明,创建一个新列表过滤掉不需要的项目通常效率更高
del list[index]
#example :-
del list[1]
请注意,我已将逻辑更改为使用
endswith
,以防止文件名路径中出现意外匹配您也可以通过内置函数执行此操作,方法如下:
file_list = ['a.txt', 'b.pdf','c.exe','d.pdf','e.mp3']
extension = '.pdf'
new_list = [x for x in file_list if x.endswith(extension)]
您也可以通过内置功能执行此操作,方法如下:
file_list = ['a.txt', 'b.pdf','c.exe','d.pdf','e.mp3']
extension = '.pdf'
new_list = [x for x in file_list if x.endswith(extension)]
如果名称为name.pdf.jpgThanks,将其更改为使用
endswith
,它将失败。如果名称为name.pdf.jpgThanks,将其更改为使用endswith
,列表理解通常比过滤器
更快。另外,filter
不会在Python3中返回列表。这真的没有什么好处,所以从那以后它就不再被广泛使用了Python1@JohnLaRooy..thanks对于反馈…:)。。。itertools
模块也一样,它在Python3中具有ifilter()
?filter
的行为类似于itertools中的ifilter
。使用列表理解和生成器表达式更容易,因为它们不需要移植在Python2和Python3之间移动列表理解通常比过滤器
更快。另外,filter
不会在Python3中返回列表。这真的没有什么好处,所以从那以后它就不再被广泛使用了Python1@JohnLaRooy..thanks对于反馈…:)。。。itertools
模块也一样,它在Python3中具有ifilter()
?filter
的行为类似于itertools中的ifilter
。使用列表理解和生成器表达式更容易,因为它们不需要在Python2和Python3之间进行移植