简体   繁体   中英

Get an element by a substring of its value in python list

I have a list like this content = ['C:\User\Folder\a.txt', 'C:\User\Folder\big_a.txt', 'C:\User\Folder\small_a.txt'] in which every item is unique, I can't have for example two C:\User\Folder\small_a.txt s, of course.
Now I want to get the item that matches the string big .
What I'm doing is

for file in content:
    if 'big' in file:
        path = file
        break

And it works.

What I ask you is: there's a different way to do that? Maybe more efficient or something in one line?
Just curiosity

This basically does the same of your code:

path = next(file for file in content if "big" in file)

You could use a list comprehension to do the same task in fewer lines, but it will not be the most optimal since it will not contain the break statement. Regardless of whichever way you chose to do (list-comprehension vs for) this will be an O(n) operation.

content = ["a.txt", "big_a.txt", "small_a.txt"]
file = next(i for i in content if "big" in i)

print(file) #> big_a.txt

I am not sure about efficiency, but this is definitely beautiful to read and write

path = [file for file in  content if 'big' in file]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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