python - 打印具有字符“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
解决方案
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']
推荐阅读
- swift - SwiftUI URLImage 库错误从核心数据展开可选值
- c# - 使用 ASP.Net Core WebApi 在两个微服务之间进行通信
- python - 使用 django 视图在模板中逐行打印循环结果
- javascript - 避免浏览器缓存javascript文件
- python - 无法使用请求从表中抓取名称
- python - 如何遍历每个数据条目并从另一个中减去每个条目?[Python]
- python - 创建不同列表的元组列表
- php - Cakephp 2 - Redis - Docker | 拒绝连接
- javascript - 从容器中删除(而不是隐藏)许多 div 的溢出,或限制容器的数量?
- node.js - Express-validator 没有在右链上中断