Python:如何在没有错误的情况下引用可选变量

标签 python variables plot legend option-type

我正在尝试为具有可变数据集的图创建图例。至少有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/

相关文章:

python - 如何修复 "plural forms could be dangerous"django 错误?

javascript - 为什么我的函数不返回用户输入的字符串

bash - 在 Bash 中使用变量作为函数参数

r - 基于 y 值的散点图颜色

python - 如何使用返回绘图的函数创建 3D 绘图?

python - 使用 Python 2.7.5 将文件夹中的所有压缩文件解压缩到同一文件夹

python - 在 python 中使用带有可变字符串的条件

python - 了解 Python 类中的变量范围

matlab - 如何在 X 轴上始终显示 "labels"

python - kivy TextInput更改字体颜色添加背景线