首页 > 解决方案 > 如何在二维数组中使用更多索引?

问题描述

我正在尝试使用更多数组索引来简化我的脚本;但是,总是得到一个 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 ...?或者没有办法做到这一点?

标签: pythonarrays

解决方案


你可以看看这个:

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角色吓倒了。这是一个类型提示,在这里,它只是为了提供清晰性。有关更多信息,请查看文档


推荐阅读