Print the elements in an array having character 'a'

Viewed 66

How do we write code to print elements containing 'a' in myarray

myarray = np.array([
  [['car','jeep','bus'],['cat','dog','rat']],
  [['apple','orange','banana'],['London','New York','Paris']]
])

I have tried using this method but I did not get any output.

import numpy as np
myarray = np.array([
  [['car','jeep','bus'],['cat','dog','rat']],
  [['apple','orange','banana'],['London','New York','Paris']]
])     
         
for i in range(0, len(myarray)):    
    print(i[0])
    if 'i' in myarray:
        print(myarray[0])
    else:
        continue
2 Answers

Credit You don't need NumPy in this situation. Below is an example of how you can traverse a deeply nested list and return each element.

x = [[['car','jeep','bus'],['cat','dog','rat']],[['apple','orange','banana'],['London','New York','Paris']]]
def traverse(a):
    if not isinstance(a, list):yield a
    else:
        for e in a:yield from traverse(e)
aWords = [string for string in [e for e in traverse(x)] if 'a' in string]

output

['car', 'cat', 'rat', 'apple', 'orange', 'banana', 'Paris']

You can do this with numpy.char.find.

np.char.find(myarray, 'a')

The output indicates the position where the character is found, or otherwise -1 if the character is absent:

array([[[ 1, -1, -1],
    [ 1, -1,  1]],

   [[ 0,  2,  1],
    [-1, -1,  1]]])

The following returns the elements where 'a' was found:

myarray[np.char.find(myarray, 'a') > -1]

Which gives the output:

array(['car', 'cat', 'rat', 'apple', 'orange', 'banana', 'Paris'],
  dtype='<U8')
Related