【发布时间】:2014-09-29 18:49:42
【问题描述】:
我有一个循环,它根据存储在列表中的星期几创建字典。代码如下所示:
days_of_theweek = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
day_count = 0
index_count = 0
hours = {}
for i in days_of_theweek:
if day_count == index_count:
the_day = days_of_theweek[index_count]
hours[the_day] = raw_input(" Enter the shift hours for " + str(the_day)+": ")
os.system('cls')
day_count += 1
index_count += 1
return hours
问题是,运行此代码只返回循环中的第一个迭代,即{Monday : some int}。我知道会发生这种情况,因为它显然在一次停止循环的迭代后命中了 return 语句。另外,我注意到删除 return 语句可以使循环正常运行,但最后没有返回任何内容,这不是很好的哈哈。我的问题是如何运行整个循环并返回完成的字典。
【问题讨论】:
-
你为什么要比较
day_count和index_count,因为它们在整个程序中总是相等的?另外,这里是i == the_day,所以day_count和index_count似乎根本没有任何目的。
标签: python loops python-2.7 for-loop dictionary