Since your code just fetches all the matches and picks the first one with:
[file for file in files if account in file][0]
You could instead use next()
to keep retrieving the next item until a match is found:
result = [next(file for file in files if account in file) for account in accountlist]
print(result)
# ['country_Laos', 'country_Maldives'] => Same output as your original code
The only problem with the above is that a StopIteration
exception will be raised if the iterator is exhausted and no match has been found. To prevent this, we can supply a default value instead, such as None
, so it returns this value instead of the exception.
[next((file for file in files if account in file), None) for account in accountlist]
Then if we wanted to filter out None
matches, we could use another list comprehension to do that:
filtered = [file for file in result if file is not None]