【发布时间】:2013-10-12 06:01:02
【问题描述】:
我正在尝试为具有可变数据集的图创建图例。至少有 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的? -
答案通常有正确的想法,但我很好奇
locals是如何定义的。locals()是一个内置函数,它返回本地符号表,一个将变量名称映射到其关联对象的字典。如果您没有在本地绑定名称,in locals将引发异常,因为in运算符不适用于函数。in locals()在语法上是正确的,但不是您在检查数组元素是否存在时想要的。除非您的数组包含作为局部变量名称的字符串。 -
到目前为止,我很高兴看到我的问题至少部分可以理解。 @thefourtheye selectedFiles 是使用 Tkinter 的对话框窗口创建的:'selectedFiles = tkFileDialog.askopenfilenames(parent=rt,title='Choose a file') selectedFiles = rt.tk.splitlist(selectedFiles)'
-
@PeterDeGlopper,我现在明白我以两种方式错误地使用了“本地人”。下面的答案与我正在寻找的答案很接近。
标签: python variables plot legend optional