Using 'in' to match an attribute of Python objects in an array

后端 未结 8 1535
傲寒
傲寒 2021-01-07 16:25

I don\'t remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,

foo in iter_attr(array of python ob         


        
8条回答
  •  甜味超标
    2021-01-07 16:32

    No, you were not dreaming. Python has a pretty excellent list comprehension system that lets you manipulate lists pretty elegantly, and depending on exactly what you want to accomplish, this can be done a couple of ways. In essence, what you're doing is saying "For item in list if criteria.matches", and from that you can just iterate through the results or dump the results into a new list.

    I'm going to crib an example from Dive Into Python here, because it's pretty elegant and they're smarter than I am. Here they're getting a list of files in a directory, then filtering the list for all files that match a regular expression criteria.

        files = os.listdir(path)                               
        test = re.compile("test\.py$", re.IGNORECASE)          
        files = [f for f in files if test.search(f)]
    

    You could do this without regular expressions, for your example, for anything where your expression at the end returns true for a match. There are other options like using the filter() function, but if I were going to choose, I'd go with this.

    Eric Sipple

提交回复
热议问题