Python - Use a variable as a list name

后端 未结 3 1721
故里飘歌
故里飘歌 2020-12-07 03:19

I have this code in python.

import sys
list1 = [\"A\", \"B\", \"C\"]
list2 = [1, 2, 3]

myarg = sys.argv[1]
print len(myarg)

I will run thi

3条回答
  •  臣服心动
    2020-12-07 04:12

    Since it is possible, and thought @Lattyware's answer is the correct one, this is how you could do it:

    import sys
    list1 = ["A", "B", "C"]
    list2 = [1, 2, 3]
    
    myarg = sys.argv[1]
    
    print len(globals().get(myarg, []))
    

    If it prints 0, then you have a bad argument on the command line.

提交回复
热议问题