Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing integer lists to python

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  

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 ?

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)
like image 392
Swati Avatar asked Mar 17 '13 10:03

Swati


2 Answers

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

# 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
like image 53
Jakub M. Avatar answered Sep 24 '22 10:09

Jakub M.


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

Example: 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:

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

Logic I think you can write yourself. :)

like image 21
Ellochka Cannibal Avatar answered Sep 26 '22 10:09

Ellochka Cannibal