将整数列表传递给python [英] Passing integer lists to python

查看:145
本文介绍了将整数列表传递给python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递2个整数列表作为输入到python程序。

I want to pass 2 lists of integers as input to a python program.

例如,(从命令行)

python test.py --a 1 2 3 4 5 -b 1 2  

此列表中的整数范围可以从1-50,列表2是List1的子集。

任何帮助/建议?是 argparse 正确的模块吗?在使用时有任何顾虑?

The integers in this list can range from 1-50, List 2 is subset of List1.
Any help/suggestions ? Is argparse the right module ? Any concerns in using that ?

我尝试过:

import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--a', help='Enter list 1 ')
    parser.add_argument('--b', help='Enter list 2 ')
    args = parser.parse_args()
    print (args.a)


推荐答案

您可以将它们作为字符串传递,
您可以使用 argparse optparse

You can pass them as strings than convert to lists. You can use argparse or optparse.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--l1', type=str)
parser.add_argument('--l2', type=str)
args = parser.parse_args()
l1_list = args.l1.split(',') # ['1','2','3','4']

示例: python prog.py --l1 = 1,2,3,4

Example: python prog.py --l1=1,2,3,4

此外,作为一行,你可以传递像1-50这样的东西,然后拆分成' - '和构造范围。
这样的东西:

Also,as a line you can pass something like this 1-50 and then split on '-' and construct range. Something like this:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--l1', type=str, help="two numbers separated by a hyphen")
parser.add_argument('--l2', type=str)
args = parser.parse_args()
l1_list_range = xrange(*args.l1.split('-')) # xrange(1,50)
for i in l1_list_range:
    print i

示例: python prog.py --l1 = 1-50

逻辑我认为你可以自己写。 :)

Logic I think you can write yourself. :)

这篇关于将整数列表传递给python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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