【问题标题】:How to use user input to access a variable?如何使用用户输入来访问变量?
【发布时间】:2020-12-07 05:56:24
【问题描述】:

我正在创建一个程序,我想在其中提示用户纽约市的行政区,并使用该行政区的一般 GPS 坐标。我的部分代码是

df.loc[0,'BOROUGH'] = input('Borough:\n')
manhattan = [40.7831, -73.9712]
brooklyn = [40.6782, -73.9442]
staten_island = [40.5795, -74.1502]
queens = [40.7282, -73.7949]
bronx = [40.8448 ,-73.8648]

我现在想使用输入响应来访问适当的坐标。例如,如果用户输入“Manhattan”,我可以使用input().lower() 的一些变体来获取相应的自治市镇数据。

我从this answer 知道,如果我想创建 使用输入的变量,我可以这样做。有没有办法访问一个变量?

【问题讨论】:

  • 为什么不使用带有“manhattan”之类的键而不是不同变量的字典呢?无论如何,globals() 是一个字典,因此您可以使用它来访问变量以及定义它。但是——这几乎总是设计不佳的标志。
  • @JohnColeman 你的评论让我想起了《指环王》中甘道夫的经典名言:“下次投身其中,让我们摆脱你的愚蠢。”我怎么没想到这超出了我的范围。谢谢。
  • 你不调用变量。你一定在想别的事。
  • 大声笑:-)。无论如何,字典是要走的路。
  • 简答:gps_coords = globals()[input('Borough:\n')](没有错误处理)。

标签: python input variable-selection


【解决方案1】:

这是在给定用户输入的情况下从集合中挑选一些数据的一种方式:

boroughs = {'manhattan':[40.7831, -73.9712],
'brooklyn': [40.6782, -73.9442],
'staten_island': [40.5795, -74.1502],
'queens': [40.7282, -73.7949],
'bronx': [40.8448 ,-73.8648]
}

while True:
    borough = input('Please enter a borough name: ').lower()
    if borough in boroughs:
        print(f'GPS coordinates of {borough} are {boroughs[borough]}')
    else:
        print(f'Unknown borough: {borough}')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多