简体   繁体   English

Python使用特定字符串从未知列表中删除元素

[英]Python remove elements from unknown list with a specific string

There are similar questions to this but not quite what im looking for. 有与此类似的问题,但不是我想要的。

Having created a list with all files from a specific path im looking to filter out anything that does not contain a specific sequence in a string. 创建了包含来自特定路径的所有文件的列表后,我试图过滤掉字符串中不包含特定序列的任何内容。

def filter():
    someFiles = os.listdir(somePath)
    listSize = len(someFiles)

    for i in range(0, listSize):
        if (".py" not in someFiles):
            someFiles.remove(i)
            print("{0}".format(someFiles))

Im aware i shouldn't be modifying the size of a list through a loop but i left it just to roughly give an idea of what i'm trying to accomplish 我知道我不应该通过循环来修改列表的大小,但是我只是为了大致了解我要完成的工作而离开了列表

I did not make it clear, the issue that im facing is that i'm not sure what approach i should be taking when trying to remove every element that does not contain ".py". 我没有说清楚,我面临的问题是我不确定在尝试删除不包含“ .py”的每个元素时应该采用哪种方法。 What I wrote above is more of a rough draft. 我在上面写的只是草稿。

for i in range(0, listSize):
    if (".py" not in someFiles):
        someFiles.remove(i)

Note that you are trying to remove i from the list. 请注意,您正在尝试从列表中删除i i will be an index of an element in the list ( 0 , 1 , etc) and not an actual element. i将在列表中(的元素的索引01 ,等等),而不是实际的元件。 This will raise an error. 这将引发错误。


Simply use list comprehension to get only the files you do need: 只需使用列表理解只得到所需要的文件:

required_files = [f for f in someFiles if '.py' in f]

You could also use filter but it will require a lambda (and also note it will return a filter object and not a list ): 您还可以使用filter但是它需要一个lambda(还要注意,它将返回一个filter对象而不是一个list ):

required_files = list(filter(lambda x: '.py' in x, someFiles))

First of all, you don't need to use for loop to iterate over a list in Python. 首先,您不需要使用for循环来迭代Python中的列表。 Simpler version of what you've done would be 您所做的工作的简单版本是

list2 = []
for filename in list1:
    if (".py" in filename):
        list2.append(filename)

but filtering a list (or more generally, an iterator) is so common, that there is Python builtin function called, unsurprisingly, filter : 但是过滤列表(或更普遍地讲,是迭代器)非常普遍,以至于有Python内置函数叫做filter

list2 = list(filter(lambda i: ".py" in i, list1))

(this would work at least in Python3) (这至少在Python3中有效)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM