1

I have a "list" of strings and I need to get a index array of all the elements of the list that equal a pattern.

I don't need to use a python list, I can use another data structure, but I don't know which.

Example:

my_list = ['foo', 'bar', 'hello', 'foo', 'goodbye']
pattern = 'foo'

And my desired result is something like:

my_mask = [True, False, False, True, False]

So I can then index a numpy array with this mask:

selected_items = my_array[my_mask]

However, having a list and doing:

my_list == pattern

Doesn't return a mask, just False.

0

4 Answers 4

2

Here is a numpy solution:

import numpy as np

my_list = np.array(['foo', 'bar', 'hello', 'foo', 'goodbye'])
pattern = 'foo'

mask = my_list == pattern
# array([ True, False, False,  True, False], dtype=bool)

my_list[mask]
# array(['foo', 'foo'], 
#       dtype='<U7')
Sign up to request clarification or add additional context in comments.

Comments

1

You have to do the looping yourself, Python containers do not support vectorized operations, so something like:

[x == pattern for x in my_list]

Comments

0

You may use a list comprehension to get the desired list as:

>>> my_list = ['foo', 'bar', 'hello', 'foo', 'goodbye']
>>> pattern = 'foo'

>>> [item==pattern for item in my_list]
[True, False, False, True, False]

Here I am iterating on the my_list list and checking equality of each element with pattern, and storing the result (True/False) in new list created through List Comprehension.

Comments

0

You can use this to create the desired list:

mask = [x==pattern for x in my_list]

which creates

[True, False, False, True, False]

alternatively you can use numpy arrays, which support the == operator the way you wanted to use it for lists:

my_list = np.array(my_list)
my_list == pattern
>>>array([ True, False, False,  True, False])

However if you want a list of indices, then you could do something like:

[i for i,x in enumerate(my_list) if x==pattern]
>>>[0, 3]

enumerate creates tuples of (index, element_at_index) from your list. In the code i is the index and x the element at that index. We save in the new list now the index i if the elment eqauls pattern

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.