将整数列表传递给python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15459997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:11:48  来源:igfitidea点击:

Passing integer lists to python

pythoncommand-lineargparse

提问by Swati

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

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

For e.g, (from command line)

例如,(从命令行)

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

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

此列表中的整数范围为 1-50,列表 2 是列表 1 的子集。
任何帮助/建议?是argparse正确的模块吗?使用它有任何顾虑吗?

I have tried :

我试过了 :

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)

采纳答案by Ellochka Cannibal

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

您可以将它们作为字符串传递而不是转换为列表。您可以使用argparseoptparse

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

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

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

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

此外,作为一条线,您可以传递类似 1-50 的内容,然后在“-”上拆分并构建范围。像这样的东西:

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

Example: python prog.py --l1=1-50

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

Logic I think you can write yourself. :)

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

回答by Inbar Rose

The way that optparseand argparsework is they read arguments from the command line, arguments are split by white-space, so if you want to input your list of integers through the command line interfact from optparseor argparse- you can do this by removing the spaces, or by surrounding your argument with ", example:

这件事的方法optparseargparse工作,他们在命令行中读取参数,参数是由空格分割,所以如果你想输入你的整数列表是通过命令行interfactoptparseargparse-您可以通过删除空格做到这一点,或用 来包围你的论点",例如:

> my_script.py --a "1 2 3 4 5" --b "1 2"

or:

或者:

> my_script.py --a 1,2,3,4,5 --b  1,2

Your script then needs to convert these inputs into an actual list.

然后,您的脚本需要将这些输入转换为实际列表。

Using argparsesyntax (very similar for optparse):

使用argparse语法(与 非常相似optparse):

# with spaces and "
a_lst = [i for i in args.a.split(' ')] 
b_lst = [i for i in args.b.split(' ')]

# without spaces and ,
a_lst = [i for i in args.a.split(',')] 
b_lst = [i for i in args.b.split(',')]


Another way to do this would be by either importing the module you want to run and passing the list objects to a class that deals with your code, or by using a while loop and raw_input/inputto collect the desired list.

另一种方法是导入要运行的模块并将列表对象传递给处理代码的类,或者使用 while 循环和raw_input/input收集所需的列表。

回答by Roland Smith

If the onlyarguments are the lists and the separators, you can do it relatively simply:

如果唯一的参数是列表和分隔符,则可以相对简单地进行:

sa = sys.argv.index('-a')
sb = sys.argv.index('-b')
lista = [int(i) for i in sys.argv[sa+1:sb]]
listb = [int(i) for i in sys.argv[sb+1:]]

Adding validation is easy:

添加验证很容易:

aval = [i for i in lista if i>1 and i<50]
if len(aval) < len(lista):
    print 'The -a list contains invalid numbers.'
bval = [i for i in listb if i>1 and i<50]
if len(bval) < len(listb):
    print 'The -b list contains invalid numbers.'

Producing a help message:

生成帮助消息:

if sys.argv[1] in ['-h', '-H'] or len(sys.argv) == 1:
    print "Usage: <name> -a [list of integers] -b [list of integers]"

回答by Jakub M.

argparsesupports nargsparameter, which tells you how many parameters it eats. When nargs="+"it accepts one or more parameters, so you can pass -b 1 2 3 4and it will be assigned as a list to bargument

argparse支持nargs参数,它告诉你它吃了多少个参数。当nargs="+"它接受一个或多个参数时,因此您可以传递-b 1 2 3 4并将其作为列表分配给b参数

# args.py
import argparse

p = argparse.ArgumentParser()

# accept two lists of arguments
# like -a 1 2 3 4 -b 1 2 3
p.add_argument('-a', nargs="+", type=int)
p.add_argument('-b', nargs="+", type=int)
args = p.parse_args()

# check if input is valid
set_a = set(args.a)
set_b = set(args.b)

# check if "a" is in proper range.
if len(set_a - set(range(1, 51))) > 0: # can use also min(a)>=1 and max(a)<=50
    raise Exception("set a not in range [1,50]")

# check if "b" is in "a"
if len(set_b - set_a) > 0:
    raise Exception("set b not entirely in set a")

# you could even skip len(...) and leave just operations on sets
# ...

So you can run:

所以你可以运行:

$ python arg.py  -a 1 2 3 4 -b 2 20
Exception: set b not entirely in set a

$ python arg.py  -a 1 2 3 4 60 -b 2
Exception: set a not in range [1,50]

And this is valid:

这是有效的:

$ python arg.py  -a 1 2 3 4 -b 2 3

回答by bobtheterrible

This worked for me:

这对我有用:

parser.add_argument('-i', '--ids', help="A comma separated list IDs", type=lambda x: x.split(','))

parser.add_argument('-i', '--ids', help="A comma separated list IDs", type=lambda x: x.split(','))

EDIT:

编辑:

I have just realised that this doesn't actually answer the question being asked. Jakubhas the correct solution.

我刚刚意识到这实际上并没有回答被问到的问题。Jakub有正确的解决方案。

回答by Allie Fitter

Just adding this one for completeness. I was surprised that I didn't see this approach.

只是为了完整性添加这个。我很惊讶我没有看到这种方法。

from argparse import Action, ArgumentParser


class CommaSeparatedListAction(Action):
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, values.split(','))


parser = ArgumentParser()
parser.add_argument('-l', action=CommaSeparatedListAction)
print(parser.parse_args('-l a,b,c,d'.split()))

# Namespace(l=['a', 'b', 'c', 'd'])

This just a basic example, but you can also add validation or transform values in someway such as coercing them to uppercase.

这只是一个基本示例,但您也可以以某种方式添加验证或转换值,例如将它们强制为大写。

from argparse import Action, ArgumentParser


class UppercaseLetterCommaSeparatedListAction(Action):
    def __call__(self, parser, namespace, values, option_string=None):
        letters = values.split(',')
        for l in letters:
            self._validate_letter(parser, l)
        setattr(
            namespace,
            self.dest,
            list(map(lambda v: v.upper(), letters))
        )

    def _validate_letter(self, parser, letter):
        if len(letter) > 1 or not letter.isalpha():
            parser.error('l must be a comma separated list of letters')


parser = ArgumentParser()
parser.add_argument('-l', action=UppercaseLetterCommaSeparatedListAction)
print(parser.parse_args('-l a,b,c,d'.split()))

# Namespace(l=['A', 'B', 'C', 'D'])

parser = ArgumentParser()
parser.add_argument('-l', action=UppercaseLetterCommaSeparatedListAction)
print(parser.parse_args('-l a,bb,c,d'.split()))

# usage: list.py [-h] [-l L]
# list.py: error: l must be a comma separated list of letters

parser = ArgumentParser()
parser.add_argument('-l', action=UppercaseLetterCommaSeparatedListAction)
print(parser.parse_args('-l a,1,c,d'.split()))

# usage: list.py [-h] [-l L]
# list.py: error: l must be a comma separated list of letters