0

I have the following python argparse parser:

pointparser = argparse.ArgumentParser(add_help=False)
pointparser.add_argument("-a", "--a_value", default="NaN", nargs="?",
                         type=float)
pointparser.add_argument("-b", "--b_value", default="NaN", nargs="?",
                         type=float)
...
pointparser.add_argument("-j", "--j_value", default="NaN", nargs="?",
                         type=float)
data_point = pointparser.parse_args(parameterlist)
datapoint=[data_point.a_value, data_point.b_value, data_point.c_value,
           data_point.d_value, data_point.e_value, data_point.f_value,
           data_point.g_value, data_point.h_value, data_point.i_value,
           data_point.j_value]

Is it possible to loop over the arguments a-j and directly store them in a list. That way, I could leave the number of arguments open, i.e. only go to -c or even to -k

4
  • Do you actually care about them being named a, b, c, etc, or do you just want the user to be able to run e.g. python yourthing.py one two three and get a list ['one', 'two', 'three']? Commented Nov 10, 2016 at 22:56
  • You really shouldn't have one variable datapoint and another data_point. Commented Nov 10, 2016 at 23:01
  • The nargs is a little odd. There doesn't seem to be any reason to specify the options without an argument, since it accomplishes the same thing as not specifying it at all. Commented Nov 10, 2016 at 23:34
  • @chepner: It avoids an error of the program if, e.g. by mistake, no argument is given. Commented Nov 11, 2016 at 6:41

1 Answer 1

1
import argparse
import math

pointparser = argparse.ArgumentParser(add_help=False)
pointparser.add_argument("-a", "--a_value", default="NaN", nargs="?",
                         type=float)
pointparser.add_argument("-b", "--b_value", default="NaN", nargs="?",
                         type=float)
pointparser.add_argument("-j", "--j_value", default="NaN", nargs="?",
                         type=float)
data_point = pointparser.parse_args()
datapoint = [value for key, value in sorted(vars(data_point).items())
             if not math.isnan(value)]
print(datapoint)  # [1.0, 2.0]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.