Passing integer lists to python

后端 未结 6 648
感情败类
感情败类 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 19:59

    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. :)

提交回复
热议问题