Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:从用户输入调用预定义变量/列表等_Python_Variables_Global Variables_Constants_User Input - Fatal编程技术网

Python:从用户输入调用预定义变量/列表等

Python:从用户输入调用预定义变量/列表等,python,variables,global-variables,constants,user-input,Python,Variables,Global Variables,Constants,User Input,提前谢谢你的帮助!Python中存在以下问题(我使用Py 3.6.5): 我有一些列表,其中有一些值。(我想使用这些值作为整个程序的预定义常量。) 在主菜单中,程序要求用户命名其中一个列表。用户写入:列表1 我想写一个函数,返回List1的第一个元素。如果用户写入List2,则函数应打印List2的第一个元素,以此类推(不需要,仅当需要获得所需结果时) 我希望代码看起来像这样。我只是想指出,用户的输入存储在“Variable”中,然后将其提供给ListCall函数 List1 = [1,2,3]

提前谢谢你的帮助!Python中存在以下问题(我使用Py 3.6.5):

  • 我有一些列表,其中有一些值。(我想使用这些值作为整个程序的预定义常量。)

  • 在主菜单中,程序要求用户命名其中一个列表。用户写入:列表1

  • 我想写一个函数,返回List1的第一个元素。如果用户写入List2,则函数应打印List2的第一个元素,以此类推(不需要,仅当需要获得所需结果时)

  • 我希望代码看起来像这样。我只是想指出,用户的输入存储在“Variable”中,然后将其提供给ListCall函数

    List1 = [1,2,3]
    List2 = [4,5,6]
    
    def ListCall(List):
        #Some Code
        print(List[0])
    
    # MAIN
    Variable = input('Please choose a List: ')
    ListCall(Variable)
    
    不知何故,我通过以下代码实现了这个期望的结果:

    List1 = [1,2,3]
    List2 = [4,5,6]
    
    Variable = vars()[(input('Please choose a List: '))]
    
    print("First element of the choosen List is: ", Variable[0])
    
    但是我很确定,这不是最优雅的方法,vars()可能不适合这种用法。
    我甚至不想使用单独的ListCall函数,如果不需要的话。。。我只希望它能用最合适的方法工作。

    您可以将列表存储在dict中:

    my_dict = {
                  "List1": [1, 2, 3],
                  "List2": [4, 5, 6]
              }
    variable = input('Please choose a List: ')
    try:
        print("First element of the choosen List is: ", my_dict[variable][0])
    except KeyError:
        print("The list " + variable + "do not exist")
    

    使用字典保存列表及其名称,而不是
    vars()
    可能重复的列表