How to find index in list by search - python

['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

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]

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

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.

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])

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.

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"

If you don't want the answer in a list.
given_list = ['16:False,', '15:False,', '17:True']
for i in range(0, len(given_list)):
if "True" in given_list[i]:
print i

Related

Get the index of the sublist when checking for the existence of an element

As a continuation for this question, how can I get the index of the sublist which contains the element?
So for example if I have:
a = [[1,2],[3,4],[5,6]]
any(2 in i for i in a)
....
How can I get 0 as a result (Because a[0] contains the number 2)?
Simple list comprehension which iterates over list with indexes using enumerate() will do the trick:
res = [i for i, el in enumerate(a) if 2 in el]
You can achieve same using regular for loop:
res = []
for i, el in enumerate(a):
if 2 in el:
res.append(el)
Alternatively, you can try this too:
for idx, sublst in enumerate(a):
if 2 in sublst:
print(idx)
Output:
0

filter a list based on values in another list

list1 = ['a','b','c','d']
list2 = [1,0,1,0]
Given two lists like the above, I would like to obtain a third list whose values are ['a','c']
In other words, I'd like the target list to be the values from list1 where the corresponding element in list2 is 1.
As noted in the comments:
[i for i, j in zip(list1, list2) if j] would work.
Alternatively, if you were looking for something not so advanced:
list3 = []
for i in range(len(list1)):
if list2[i] == 1:
list3.append(list1[i])
Use enumerate function on second list to include index, which can be used for the first list.
[list1[i] for i, item in enumerate(list2) if item]
Generators can be nice if you have very long lists:
def filterfunc(a, b, keyvalue=1):
return (x for i, x in enumerate(a) if b[i] == keyvalue)
To get the whole sequence:
list(filterfunc(a, b))

python - keep "other" element in a list under if conditions

I have a list of strings like the following:
L = ['aa','bb','cc']
I would like to apply an if condition on its elements to check if multiple strings are in it, and then keep only one element as result. The pseudo-code I'm trying to implement is:
if 'aa' in L AND 'cc' in L:
return the third element (i.e. 'bb')
else:
return 'aa'
So far I've been working with a list comprehension like:
return = ['aa' if elem != 'aa' and elem != 'cc' else elem for elem in L][0]
But it doesn't work as expected.
EDIT:
Fixed return as element and not a list.
I don't think you can do this with a single list comprehension. How about:
L = ['aa','bb','cc']
if "aa" in L and "cc" in L:
result = [item for item in L if item != "aa" and item != "cc"][0]
else:
result = "aa"
return result
Or return [item for item in L if item != "aa" and item != "cc"][0] if "aa" in L and "cc" in L else "aa" if you insist on doing it in one line.
You could find the difference between your lists using sets:
l = ['aa','bb','cc']
k = ['aa','cc']
if len(list(set(l) - set(k))) == 1:
return list(set(l) - set(k))
else:
return l[0]
If they return exactly one element return that, otherwise the first element of l.

Splitting a list with a separator

I have written a function that gets two arguments: a list and one value that is present in the list previously given (sep). The purpose of the function is to split the given list and return multiple lists in list without the value that was specified in the second argument of the written fuction. So with def split_list([1,2,3,2,1],2) ---> result would be [[1],[3],[1]]. The functionality of spliting is good but the result keeps the second value of the function (sep) in the separated lists. I couldnt think of a way how to solve this problem. Thanks in advance
def split_list(l, sep):
occurence = [i for i, x in enumerate(l) if x == sep]
newlist=[]
newlist.append(l[:occurence[0]])
for i in range(0,len(occurence)):
j=i+1
if j < len(occurence):
newlist.append(l[occurence[i]:occurence[j]])
i+=1
newlist.append(l[occurence[-1]:])
return newlist
How about this:
def split_list(l, sep):
nl = [[]]
for el in l:
if el == sep:
nl.append([])
else:
# Append to last list
nl[-1].append(el)
return nl
Or with your method, by using the list of occurences:
def split_list(l, sep):
# occurences
o = [i for i, x in enumerate(l) if x == sep]
nl = []
# first slice
nl.append(l[:o[0]])
# middle slices
for i in range(1, len(o)):
nl.append(l[o[i-1]+1:o[i]])
# last slice
nl.append(l[o[-1]+1:])
return nl
you can split your list with below list comprehension and zip function :
>>> l=[1,2,3,2,1,8,9]
>>> oc= [i for i, x in enumerate(l) if x == 2]
>>> [l[i:j] if 2 not in l[i:j] else l[i+1:j] for i, j in zip([0]+oc, oc+[None])]
[[1], [3], [1, 8, 9]]
So for your function :
def split_list(l, sep):
occurence = [i for i, x in enumerate(l) if x == sep]
return [l[i:j] if sep not in l[i:j] else l[i+1:j] for i, j in zip([0]+occurence, occurence+[None])]
Use [list(x) for i, x in enumerate(l) if x != sep]

dealing with an empty list inside a list

I have a list which looks something like this:
mylist = ([(0.1, 0.5),(0.4, 1.0)], [(0.2, 0.4),(0.15, 0.6)], None, [(0.35, 0.8),(0.05, 1.0)])
What I would like to know is how do I check for the empty entry or None in the list and if there is one then it should continue further ignoring it. Something like,
if mylist == something :
do this
if mylist == [] or () or None :
ignore and continue
I am not able to put that into a code. Thank you.
Basically, in python
[], (), 0, "", None, False
all of these means that the value is False
Therefore:
newList = [i for i in myList if i] # this will create a new list which does not have any empty item
emptyList = [i for i in myList if not i] # this will create a new list which has ONLY empty items
or as you asked:
for i in myList:
if i:
# do whatever you want with your assigned values
else:
# do whatever you want with null values (i.e. [] or () or {} or None or False...)
and then you can do whatever you want with your new list :)
for sublist in mylist:
if sublist is None:
#what to do with None
continue
elif not sublist and isinstance(sublist, list):
#what to do if it's an empty list
continue
elif not isinstance(sublist, list):
#what to do if it's not a list
continue
#what to do if it's a list and not empty
Alternatively, you could leave out the 'continues' and put the general case in an else clause, only check for some of the possible circumstances, or nest the ifs.
Generally, if you knew you'd only get None or a container, just if not sublist: continue is adequate to ignore empty containers and None. To filter these values out of the list, do
mylist = [sublist for sublist in mylist if sublist]
Edit: You can't do this in the update function. You should pre-filter the list. Where you have
mylist = oldlist[:]
replace it with
mylist = [sublist for sublist in oldlist if sublist]
If the row name a, b, or whatever is there, but the rest is empty / None, then do
mylist = [sublist for sublist in oldlist if sublist[1]]
and this will filter on the truth value of the 2nd item intead of the first item / row title.
I will just do this:
for x in mylist:
if not x:
continue
#--> do what you want to do
but I have to say the first answer with comprehension list is more clean unless you need to do a complicated stuff inside the for statement.
How about this piece of code:
for x in mylist:
if x is None or x == [] or x == ():
continue
else:
do this

Categories