Reputation: 716
I have a list that has string type items in its sublists.
mylist = [["Apple"],["Apple"],["Grapes", "Peach"],["Banana"],["Apple"], ["Apple", "Orange"]]
I want to get the indices of sublist that has Apple
only.
This is what I have tried so far:
get_apple_indices = [i for i, x in enumerate(list(my_list)) if x == "Apple"]
print(get_apple_indices)
Actual output:
[]
Expected output:
[0,1,4]
Upvotes: 1
Views: 64
Reputation: 252
Assuming you really do need to match on string instead of a list for some reason, here is a solution.
From just-so-snippets:
match_string = "Apple"
get_matching_indices = [i for i, x in enumerate(list(mylist)) if len(x) == 1 and x[0] == match_string]
You can see that it checks for sublists that have a length of 1 (if it has only "Apple", then it must have a length of 1), then it checks to see if the first (only) item matches the string.
Upvotes: 0
Reputation: 51894
perhaps compare each element against a single-item list ['Apple']
instead of comparing a list
object against a string
.
get_apple_indices = [i for i, x in enumerate(list(my_list)) if x == ["Apple"]]
Upvotes: 1