首页 > 解决方案 > 打印具有字符“a”的数组中的元素

问题描述

我们如何编写代码来打印 myarray 中包含“a”的元素

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

我尝试过使用这种方法,但没有得到任何输出。

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

标签: pythonarraysnumpy

解决方案


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

推荐阅读