【发布时间】:2015-04-23 18:53:20
【问题描述】:
我想知道最pythonic的方法是什么:
拥有一个字符串列表和一个子字符串列表会删除字符串列表中包含任何子字符串列表的元素。
list_dirs = ('C:\\foo\\bar\\hello.txt', 'C:\\bar\\foo\\.world.txt', 'C:\\foo\\bar\\yellow.txt')
unwanted_files = ('hello.txt', 'yellow.txt)
期望的输出:
list_dirs = (C:\\bar\\foo\.world.txt')
我曾尝试实施类似的问题,例如this,但我仍在努力进行删除并将该特定实施扩展到列表中。
到目前为止,我已经这样做了:
for i in arange(0, len(list_dirs)):
if 'hello.txt' in list_dirs[i]:
list_dirs.remove(list_dirs[i])
这可行,但可能不是更简洁的方式,更重要的是它不支持列表,如果我想删除 hello.txt 或 yellow.txt,我将不得不使用 or。谢谢。
【问题讨论】:
-
@PM 2Ring 是的,我使用的是 numpy。 arange 类似于 range
-
修改您正在迭代的集合是不安全的。
标签: python string list numpy substring