简体   繁体   中英

Python argument parser list of list or tuple of tuples

I'm trying to use argument parser to parse a 3D coordinate so I can use

--cord 1,2,3 2,4,6 3,6,9

and get

((1,2,3),(2,4,6),(3,6,9))

My attempt is

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--cord', help="Coordinate", dest="cord", type=tuple, nargs=3)
args = parser.parse_args(["--cord","1,2,3","2,4,6","3,6,9"])

vars(args) 
{'cord': [('1', ',', '2', ',', '3'),
  ('2', ',', '4', ',', '6'),
  ('3', ',', '6', ',', '9')]}

What would the replacement of the comma be?

You can add your own type . This also allows for additional validations, for example:

def coords(s):
    try:
        x, y, z = map(int, s.split(','))
        return x, y, z
    except:
        raise argparse.ArgumentTypeError("Coordinates must be x,y,z")


parser.add_argument('--cord', help="Coordinate", dest="cord", type=coords, nargs=3)

For my problem, I had to have a more general approach, not linked to the number of inputs.

Starting from the great answer by georg, I solved my problem as follows

# additional type
def coords(s):
    seps = r'[ ;.]'
    try:
        situp = []
        for si in re.split(seps, s):
            situp.append(tuple(map(int, si.split(','))))
        return situp
    except:
        raise argparse.ArgumentTypeError("Coordinates must be given divided by commas and space, dot, or semicolon e.g.: 'x,y k,l,m'")

With this, an input like 1,2 3,4,5 will be turned in a list of tuples like [(1,2), (3,4,5)]

EDIT: It might be that the for loop is not optimal, but I wrote it to avoid the use of nargs

EDIT 2:

  1. to have a list of list, one should change

    the line situp.append(tuple(map(int, si.split(','))))

    with situp.append(list(map(int, si.split(','))))

  2. to have a tuple of uples one can just change the return with

    return tuple(situp)

我不能在这里发表评论,但想建议在 georgs 答案中添加 soneting,因为可能会出现一些混淆,因为 x,y,z 通常被假定为标量值而不是向量或 3 项数组,即如果在这个解决方案中你想要要读取 x,y,z (如异常告诉您的那样),您会想到 1.0,2.0,3.0 之类的东西,您需要 nargs=1。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM