Home > database >  How to find index in list by search
How to find index in list by search

Time:08-24

['16:False,', '15:False,', '17:True,']

I need to know the index of str with true value

It is at index 2 but how do i make code like this for that

CodePudding user response:

Not sure if this is what you're asking for, but this will return the index of all items in the list with "True" in them:

my_list = ['16:False,', '15:False,', '17:True,']

indexes = [idx for idx, s in enumerate(my_list) if "True" in s]

print(indexes)

>>> [2]

CodePudding user response:

Try next():

lst = ["16:False,", "15:False,", "17:True,"]


i = next((i for i, s in enumerate(lst) if "True" in s), None)
print(i)

Prints:

2

If "True" isn't found, i is set to None

CodePudding user response:

You can use a list comprehension and the in command as such,

my_list = ['16:False,', '15:False,', '17:True,']
idx = [i for i, ele in enumerate(my_list) if "True" in  ele]

print(idx)

The comprehension clocks through your list & takes note of the indices where the element, ele contains the string "True".

If there is more than one entry then you will get a list of indices, if there are no entries then you will get an empty list.

CodePudding user response:

Another possible solution:

import numpy as np

l = ['16:False,', '15:False,', '17:True,']

np.where(['True' in x for x in l])[0]

#> array([2])

CodePudding user response:

You can do it like this:

def find_true_index(lst):
    for index, elem in enumerate(lst):
        if 'True' in elem:
            return index
    return None

l = ['16:False,', '15:False,', '17:True,']

print(find_true_index(l))

It will return the index if it found it and None if it didn't. Although be careful as this will always only find the first occurance, it might be useful to add all the wanted indexes to the list and then return the list.

CodePudding user response:

def get_true_index_list(data: list, only_first=False):
    trues_list = []
    for i, v in enumerate(data):
        if 'True' in v:
            true_index = int(v.split(':')[0])
            if only_first:
                return (i, true_index) 
            trues_list.append((i, true_index)
    return trues_list
r1 = get_true_index_list(['16:True,', '15:False,', '17:True,'])
r2 = get_true_index_list(['16:False,', '15:False,', '17:True,'], only_first=True)
print(r1)
print(r2)

Result :

([(0,16),(2,17)])
(2,17)

Here, first value of tuple is lists's index and second value is int value in "True"

  • Related