Python - Use a variable as a list name

后端 未结 3 1707
故里飘歌
故里飘歌 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:03

    You shouldn't, but if you really want/have to do this, you can use globals():

    print len(globals()[myarg])
    

    First make sure myarg is the name of a declared variable: if myarg in globals(): ...

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 04:20

    While this is entirely possible in Python, it's not needed. The best solution here is to not do this, have a dictionary instead.

    import sys
    
    lists = {
        "list1": ["A", "B", "C"],
        "list2": [1, 2, 3],
    }
    
    myarg = sys.argv[1]
    print len(lists[myarg])
    

    You note you have 13 lists in your script - where you have lots of similar data (or data that needs to be handled in a similar way), it's a sign you want a data structure, rather than flat variables. It will make your life a lot easier.

    0 讨论(0)
提交回复
热议问题