python - 如何在二维数组中使用更多索引?
问题描述
我正在尝试使用更多数组索引来简化我的脚本;但是,总是得到一个 IndexError。这是我的脚本的一部分:
# Set the values in x-axis, only for the first plot
axs[0].set_xlim(0, 1200)
axs[0].set_ylim(-800, 200)
# Set the range of values in x-axis
axs[0].xaxis.set_major_locator(MultipleLocator(50))
# Set the values in y-axis, only for the rest
axs[1].set_xlim(0, 1200)
axs[1].set_ylim(0, 9)
axs[2].set_xlim(0, 1200)
axs[2].set_ylim(0, 9)
好吧,我认为这些行可以更简化。例如,使用:
axs[1,2].set_ylim(0, 9)
其中 y 轴的范围为 0-9;但是,当我尝试这样做时,我遇到了错误:
IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed
我部分理解错误;但是,我对这篇文章的问题是:
有没有办法解决这个问题,在一行中使用 ...[1,2]set_ylim ...?或者没有办法做到这一点?
解决方案
你可以看看这个:
def set_ylims(indices: list, vals: tuple):
for i in indices: # For each passed index
axs[i].set_ylim(*vals) # Unpack vals and call set_ylim()
例如:
my_indices = [2,5,8]
set_ylims(my_indices, (0,9))
以防万一,如果你被我的indices: list
角色吓倒了。这是一个类型提示,在这里,它只是为了提供清晰性。有关更多信息,请查看文档。
推荐阅读
- typescript - 通过静态字段初始化器避免类之间的依赖循环
- android - 自定义 EditText 到 Android
- ios - 如何使用 iPhone X 在我的应用程序中保存不同的 faceID 并稍后将它们与任何面部匹配 - iOS Swift
- php - 网站速度很慢,但如果我修改 URL,它会正常加载
- salesforce - 在字符串中使用自定义标签会引发“字段完整性异常”
- java-8 - 使用函数式编程对列表中的服务器对象进行流和过滤
- list - 当我尝试将字符列表转换为整数列表时,值会发生变化。我该如何解决?
- c# - ASP.NET 无法从 smtp 发送电子邮件
- node.js - 有没有办法隐藏 node.js 代码
- asynchronous - 是否可以实现异步 Outlook 插件 FormRegionShowing 事件处理程序?