[英]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我正在尝试使用参数解析器来解析 3D 坐标,以便我可以使用
--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)]
有了这个,像
1,2 3,4,5
这样的输入将变成像[(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
编辑:可能是 for 循环不是最佳的,但我写它是为了避免使用
nargs
EDIT 2:编辑2:
to have a list of list, one should change有一个列表列表,一个人应该改变
the line situp.append(tuple(map(int, si.split(','))))
线
situp.append(tuple(map(int, si.split(','))))
with situp.append(list(map(int, si.split(','))))
与
situp.append(list(map(int, si.split(','))))
to have a tuple of uples one can just change the return with有一个 uples 元组,你可以改变回报
return tuple(situp)
我不能在这里发表评论,但想建议在 georgs 答案中添加 soneting,因为可能会出现一些混淆,因为 x,y,z 通常被假定为标量值而不是向量或 3 项数组,即如果在这个解决方案中你想要要读取 x,y,z (如异常告诉您的那样),您会想到 1.0,2.0,3.0 之类的东西,您需要 nargs=1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.