我正在尝试为具有可变数据集的图创建图例。至少有2个,最多5个。前两个会一直存在,但其他三个是可选的,那么如何只为现有数量的数据集创建图例?
我试过 if 语句告诉 python 如果该变量不存在该怎么做,但没有用。也许这不是确定变量存在的正确方法。
line1 = os.path.basename(str(os.path.splitext(selectedFiles[0])[0]))
line2 = os.path.basename(str(os.path.splitext(selectedFiles[1])[0]))
if selectedFiles[2] in locals:
line3 = os.path.basename(str(os.path.splitext(selectedFiles[2])[0]))
else: line3 = None
if selectedFiles[3] in locals:
line4 = os.path.basename(str(os.path.splitext(selectedFiles[3])[0]))
else: line4 = None
if selectedFiles[4] in locals:
line5 = os.path.basename(str(os.path.splitext(selectedFiles[4])[0]))
else:line5 = None
legend((line1, line2, line3, line4, line5), loc='upper left')
这是我得到的错误:
if selectedFiles[2] in locals:
IndexError: tuple index out of range
他的代码可能存在多个问题(不确定“无”是否是处理不存在数据的正确方法)。请记住,我是 python 的新手,在其他方面几乎没有编程经验,所以请耐心等待,尽量不要居高临下,因为一些更有经验的用户往往会这样做。
最佳答案
因为selectedFiles是一个tuple,里面每一项的处理逻辑是一样的。您可以使用 for 循环对其进行迭代。
lines = [os.path.basename(str(os.path.splitext(filename)[0])) for filename in selectedFiles]
#extend lines' length to 5 and fill the space with None
lines = lines + [None] * (5-len(lines))
legend(lines,loc='upper left')
关于Python:如何在没有错误的情况下引用可选变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19331093/