Passing integer lists to python

后端 未结 6 634
感情败类
感情败类 2021-01-07 19:23

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

For e.g, (from command line)

python test.py --a 1 2 3 4 5 -b 1 2  
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-07 20:10

    If the only arguments 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:  -a [list of integers] -b [list of integers]"
    

提交回复
热议问题