压缩刻度线不允许更改其属性
Zipping ticklines does not allow to change their properties
当我偶然发现一个奇怪的结果时,我正试图减少我的代码占用空间以使其更具可读性。如果我运行下面的代码:
y1 = np.linspace(1,1000)
y2 = np.linspace(10,1)
c = ["b","g"]
fig, ax = plt.subplots()
ax.plot(y1, c[0])
ax2 = ax.twinx()
ax2.plot(y2, c[1])
for tl in ax.yaxis.get_ticklines():
tl.set_color(c[0])
for ts in ax.yaxis.get_ticklabels():
ts.set_color(c[0])
我得到以下输出:
但是,当我尝试压缩它以使用以下代码减少代码量时:
for t in zip(ax.yaxis.get_ticklines(),ax.yaxis.get_ticklabels()):
t[0].set_color(c[0]),t[1].set_color(c[0])
所有的刻度标签都改变了,但只有一些刻度线(那些没有改变的标记为红色)。为什么压缩刻度线会导致其中一些发生变化?
我猜,ax.yaxis.get_ticklines()
的数量是 ax.yaxis.get_ticklabels()
的两倍,所以 zip 只是在绘制它们之前停止,而单个循环很好。
zip
的这种行为在 Python documentation 中进行了解释。
当我偶然发现一个奇怪的结果时,我正试图减少我的代码占用空间以使其更具可读性。如果我运行下面的代码:
y1 = np.linspace(1,1000)
y2 = np.linspace(10,1)
c = ["b","g"]
fig, ax = plt.subplots()
ax.plot(y1, c[0])
ax2 = ax.twinx()
ax2.plot(y2, c[1])
for tl in ax.yaxis.get_ticklines():
tl.set_color(c[0])
for ts in ax.yaxis.get_ticklabels():
ts.set_color(c[0])
我得到以下输出:
但是,当我尝试压缩它以使用以下代码减少代码量时:
for t in zip(ax.yaxis.get_ticklines(),ax.yaxis.get_ticklabels()):
t[0].set_color(c[0]),t[1].set_color(c[0])
所有的刻度标签都改变了,但只有一些刻度线(那些没有改变的标记为红色)。为什么压缩刻度线会导致其中一些发生变化?
我猜,ax.yaxis.get_ticklines()
的数量是 ax.yaxis.get_ticklabels()
的两倍,所以 zip 只是在绘制它们之前停止,而单个循环很好。
zip
的这种行为在 Python documentation 中进行了解释。