Parse a nested list with python argparse

混江龙づ霸主 提交于 2019-12-10 22:51:14

问题


Assume that I am expecting a list of lists where the inner lists have different types and lengths, e. g.,

[[1, 2], ["foo", "bar"], [3.14, "baz", 20]]

how can I parse the above list using argparse?

Most useful questions on stackoverflow:

Similar questions exist, where most useful one is here. But they are not good enough in my case as they ignore the fact that the list is nested with different data types and lenghts.


回答1:


expanding on my comment:

from argparse import ArgumentParser
import json

parser = ArgumentParser()
parser.add_argument('-l', type=json.loads)
parser.parse_args(['-l', '[[1,2],["foo","bar"],[3.14,"baz",20]]'])

prints:

Namespace(l=[[1, 2], ['foo', 'bar'], [3.14, 'baz', 20]])


来源:https://stackoverflow.com/questions/57112608/parse-a-nested-list-with-python-argparse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!