简体   繁体   English

元组的元组作为argparse命令行参数

[英]Tuple of tuples as argparse command line argument

I need users to provide a list of lists of numbers as command line arguments. 我需要用户提供数字列表的列表作为命令行参数。

The current solution I'm adopting is here below, the question is whether there is a more pythonic or more standard way of doing it. 我正在采用的当前解决方案在下面,问题是是否有更Python化或更标准的方式来实现。

Currently I'm accepting a comma-separated list of space-separated numbers from command line, like this: 目前,我从命令行接受以逗号分隔的空格分隔数字列表,如下所示:

$ python foo.py --numbers '1 2 3, 4 5 6'

and internally I do 在内部

def list_of_lists(arg):
    return map(lambda l: map(float, l), map(str.split, a.split(',')))

parser.add_argument('--numbers', type=list_of_lists)

to transform the string "1 2 3, 4 5 6" into [[1,2,3],[4,5,6]] . 将字符串"1 2 3, 4 5 6"转换为[[1,2,3],[4,5,6]]

What you have is fine. 你所拥有的一切都很好。 If I were writing it, I'd use commas and semicolons as delimiters (being strict about it: no whitespace allowed), and use a list comprehension for parsing: 如果我正在编写它,我将使用逗号和分号作为分隔符(对此严格要求:不允许使用空格),并使用列表推导进行解析:

def list_of_lists(arg):
    return [float(x.split(',')) for x in arg.split(';')]

but that's really just cosmetic. 但这实际上只是装饰。

The next question is: how much verification do you want to do in list_of_lists ? 下一个问题是:您要在list_of_lists多少次验证? Right now, this simple version assumes that the string is in exactly the format you want. 现在,这个简单的版本假定字符串的格式与您想要的格式完全相同。 You can add more logic to catch errors, raising argparse.ArgumentTypeError to signal incorrect values. 您可以添加更多逻辑来捕获错误,并引发argparse.ArgumentTypeError以指示错误的值。

Try action="append" and use --numbers more than once. 尝试使用action="append"并多次使用--numbers

This stores a list, and appends each argument value to the list. 这将存储一个列表,并将每个参数值附加到列表中。 This is useful to allow an option to be specified multiple times. 这对于允许多次指定选项很有用。

import argparse

def to_list(arg):
    return [int(i) for i in arg.split(",")]

parser = argparse.ArgumentParser()
parser.add_argument("--numbers", action="append", type=to_list)
parsed = parser.parse_args("--numbers 1,2,3 --numbers 4,5,6".split())
print(parsed)

Output: 输出:

Namespace(numbers=[[1, 2, 3], [4, 5, 6]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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