【问题标题】:Print variable from other file with raw_input使用 raw_input 从其他文件打印变量
【发布时间】:2013-07-20 20:14:51
【问题描述】:

所以我只是在这里开始一个项目。首先,我有两个文件。

第一个文件是 myDict.py。在那里我存储了我希望能够获取的变量。 myDict.py:

numbers = [1, 5, 8, 61]
wallet = [20, 50, 100, 1000]

所以我在那个文件中有两个列表,现在是主文件。我想从 raw_input 中选择要打印的列表,但我不知道如何才能做到这一点。我没有直接得到任何地方,因为我不知道如何做到这一点。

我知道我可以这样做来打印 myDict.py 中的选定变量:

import myDict
print myDict.wallet

但我找不到使用 raw_input 的方法。

【问题讨论】:

    标签: python python-2.7 python-import raw-input


    【解决方案1】:

    您可以使用getattr() function 从模块中获取以变量命名的任意属性:

    import myDict
    
    list_name = 'wallet'
    print getattr(myDict, list_name)
    

    只需使用raw_input() 向用户询问walletnumbers 即可!

    import myDict
    
    list_name = raw_input('wallet or numbers? ')
    print getattr(myDict, list_name)
    

    您可能想使用try:/except AttributeError: 来捕捉错误:

    list_name = raw_input('wallet or numbers? ')
    try:
        print getattr(myDict, list_name)
    except AttributeError:
        print "Sorry, no such list"
    

    【讨论】:

    • 非常感谢!不知道这个功能,但它肯定是我需要的!现在我可以继续这个项目了 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2021-06-21
    • 2017-09-15
    • 1970-01-01
    相关资源
    最近更新 更多