سؤال

I am trying to create a legend for a plot with variable sets of data. There are at least 2, and at most 5. The first two will always be there, but the other three are optional, so how can I create a legend for only the existing number of data sets?

I've tried if-statements to tell python what to do if that variable doesn't exist, but without avail. Perhaps this is not the proper way to determine variable existence.

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')

Here is the error I am getting:

     if selectedFiles[2] in locals:
IndexError: tuple index out of range

It is possible that there are multiple issues with his code (not sure if the "None" is the right way to handle the non-existent data). Please bear in mind that I'm am new to python with little programming experience otherwise, so bear with me and try not to condescend, as some more experienced users tend to do.

هل كانت مفيدة؟

المحلول

Because selectedFiles is a tuple, and the logic of processing each item inside it is same. you can iterate it with a for loop.

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')

نصائح أخرى

I have no idea what your data structures look like, but it looks like you just want

lines = (os.path.basename(str(os.path.splitext(x)[0])) for x in selectedFiles)

legend(lines, loc='upper left')

I would prefer this way.

line = []

for i in range(5):
  if i < len(selectedFiles):
    line.append(os.path.basename(str(os.path.splitext(selectedFiles[i])[0])))
  else:
    line.append(None)

legend(tuple(line), loc='upper left')

or you can always use except IndexError:.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top