Search code examples
pythonlistindexingstartswith

How do I get indices of values where function startswith() is true?


How do I get the indices of the value where the function "startswith()" is true?

For example: say I have a list list = ['gene1' , 'gene2' , '0.3', '', '2.3','','0.4'].

I want to print the value and the index of that value for gene 1 and gene 2 if the float starts with "0.".

Right now I have :

s = line.rstrip("\r\n").split(',')
e = [a.replace(" ", "") for a in s]
for i in e:
    if i.startswith("0."):
        print "e[0],e[1], i

But that gives me just 1 value and the 2 genes.

I would like to print:

gene1, gene2, 2, 0.3, 6, 0.4

where 2 is the index where 0.3 occurs, and 6 is the index where 0.4 occurs.


Solution

  • Use a list comprehension and enumerate:

    indices = [index for index, s in enumerate(e) if s.startswith("0.")]