将for的索引分配给变量名词

时间:2014-05-08 00:43:44

标签: python

我有这些变量:

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))中,我想使用索引' i'从for到命名变量时间,如time1,time2,time3 ......

有任何线索吗?

2 个答案:

答案 0 :(得分: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)))

答案 1 :(得分:1)

您可以将时间变量放在一个列表中(实际上,将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)))