Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find indexes of string in lists which starts with some substring?

Tags:

python

I have some list like this:

lines = [
    "line",
    "subline2",
    "subline4",
    "line",
]

And I want to take list of index of lines which starts with some substring.

I use this approach:

starts = [n for n, l in enumerate(lines) if l.startswith('sub')]

but maybe anybody knows more beautiful approach?

like image 253
kharandziuk Avatar asked Feb 22 '13 11:02

kharandziuk


1 Answers

While I like your approach, here is another one that handles identical entries in lines correctly (i.e. similar to the way your sample code does), and has comparable performance, also for the case that the length of lines grows:

starts = [i for i in range(len(lines)) if lines[i].startswith('sub')]
like image 180
Dirk Herrmann Avatar answered Sep 23 '22 06:09

Dirk Herrmann