【问题标题】:Assigning index of a for to a variable noun将 for 的索引分配给变量名词
【发布时间】:2014-05-08 00:43:43
【问题描述】:

我有这个变量:

time1 = end_time1 - start_time1
...
time2 = end_time2 - start_time2
...
time3 = end_time3 - start_time3
...
time4 = end_time4 - start_time4
...
time5 = end_time5 - start_time5

我想这样做:

for i in range(5):
    print ("Search for " + str(i) + " element(s), has taken: " + "{0:.2f}".format(round(time,2)))

但是,在format(round(time,2)) 中,我想使用 for 中的索引 'i' 来命名变量 time,例如 time1、time2、time3...

有什么线索吗?

【问题讨论】:

  • 我认为您应该使用适当的数据结构,例如列表或字典
  • 这是另一种选择,当然更好,哈哈,但无论如何,我想知道我该怎么做。谢谢。

标签: python


【解决方案1】:

您可以使用locals()

for i in range(5):
    print ("Search for " + str(i) + " element(s), has taken: " + "{0:.2f}".format(round(locals()['time'+str(i+1)],2)))

【讨论】:

  • 好的,这“有效”。我的意思是,我使用了globals(),但我得到了同样的错误:Key Error。所以我将globals() 更改为locals(),一切都很完美。非常感谢。
  • @Zariweya,很高兴能帮上一点忙(有点)
【解决方案2】:

您可以将时间变量放在一个列表中(实际上,首先将 timeX 变量作为一个列表而不是单独的变量可能是有利的)。

times = [time1, time2, time3, time4, time5]

for i in range(5):
    print ("Search for " + str(i) + " element(s), has taken: " + \
           "{0:.2f}".format(round(times[i],2)))

【讨论】:

  • 也感谢您的回答。也是正确的做法。
猜你喜欢
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多