使用 python argparse 解析嵌套列表 [英] Parse a nested list with python argparse

查看:33
本文介绍了使用 python argparse 解析嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我期待一个列表列表,其中内部列表具有不同的类型和长度,例如.g.,

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]]

如何使用 argparse 解析上面的列表?

how can I parse the above list using argparse?

关于 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.

推荐答案

扩展我的评论:

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]]'])

印刷品:

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

这篇关于使用 python argparse 解析嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆