Reputation: 14399
I've got a list of strings dumped by readlines()
and I want to find the index of the first line that includes a substring, or the last line.
This works, but seems clunky:
fooIndex=listOfStrings.index((next((x for x in listOfStrings if "foo" in x),listOfStrings[-1])))
There has to be a better way than searching twice, but I can't find it.
Upvotes: 3
Views: 4566
Reputation: 82949
I don't think there is a good (i.e. readable) one-line solution for this. Alternatively to @eugene's loop, you could also use a try/except
.
def get_index(list_of_strings, substring):
try:
return next(i for i, e in enumerate(list_of_strings) if substring in e)
except StopIteration:
return len(list_of_strings) - 1
The code is a little longer, but IMHO the intent is very clear: Try to get the next index that contains the substring, or the length of the list minus one.
Update: In fact, there is a good (well, somewhat okay-ish) one-liner, and you almost had it, using the default
parameter of next
, but instead of using the last element itself as default, and then calling index
, just put the index itself and combine with enumerate
:
next((i for i, e in enumerate(list_of_strings) if substring in e),
len(list_of_strings) - 1)
Upvotes: 3
Reputation: 150128
Using enumerate()
in a function would be both more readable and efficient:
def get_index(strings, substr):
for idx, string in enumerate(strings):
if substr in string:
break
return idx
Note that you don't need to call .readlines()
on a file object to iterate over the lines — just use it as an iterable.
Upvotes: 2