如何在不使用字典的情况下将字符串转换为python中的变量?

时间:2021-02-23 15:21:30

标签: python python-3.x

在我的代码中,我有一些变量,例如 Up1、Up2 ..... 等等。 这与购买火车票有关。 用户以整数形式输入时间,如下所示,但不是以 (hh:mm) 形式输入的全时间 我希望python从用户那里获取整数输入,用字符串'Up'(这里是整数)附加它以创建上面提到的变量,例如9:00 Up9 现在python需要找到该特定列车的座位数,并比较用户输入的座位数是否在可用座位范围内。 但是在行中(而 Tickets_to_buy > Uptime_:),Uptime_ 是一个字符串,python 拒绝它。 如何将此 str(Uptime_) 转换为变量名称,而不是 str(Up9) 它将成为变量 (Up9) 并且 python 获取其值以将其与其他变量进行比较...

Uptime = int(input('''Please enter the time of uptime from below:
    9 for 09:00
    1 for 11:00
    3 for 03:00
    5 for 15:00'''))
Downtime = int(input('''Please enter the time of downtime from below:
    0 for 10:00
    2 for 12:00
    4 for 14:00
    6 for 16:00'''))

Uptime_ = ('UP' + str(Uptime))

Tickets_to_buy = 0

while Tickets_to_buy > Uptime_:
    Tickets_to_buy = int(input('Please enter number of tickets you would like to buy. It should be less than', Uptime_)) 

1 个答案:

答案 0 :(得分:0)

不知道你为什么不喜欢字典......但你也可以在这里使用元组:

您现在有变量:

UP1 = varFor1
UP9 = varFor9

改为将其设为与您的用户输入直接相关的元组:

varList = ((9, varFor9), (1, varFor1))

现在,在您的代码中,您只需将 Uptime_ 设置为:

for each in varList:
     if each[0] = Uptime:
          Uptime_ = each[1]

话虽如此,如果您将变量输出设置为字典:

varList = { 9 : "varFor9", 1 : "varFor1" }

你可以做同样的事情,但仍然在一行中分配 Uptime_:

Uptime_ = varList[Uptime]

而且,每当您处理用户输入时,您可能想要在尝试执行输入的位置周围放置一个 try/except,以防胖手指或输入您不想要/不期望的值.