【问题标题】:Returning a dictionary from a loop从循环中返回字典
【发布时间】: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_countindex_count,因为它们在整个程序中总是相等的?另外,这里是i == the_day,所以day_countindex_count 似乎根本没有任何目的。

标签: python loops python-2.7 for-loop dictionary


【解决方案1】:

Python 对缩进级别很敏感。将return hours 语句移出for-loop

def get_hours():
    days_of_theweek = ["Monday", "Tuesday", "Wednesday", "Thursday",
                       "Friday", "Saturday", "Sunday"]
    hours = {}

    for the_day in days_of_theweek:
        prompt = "  Enter the shift hours for {}: ".format(the_day)
        hours[the_day] = int(raw_input(prompt))
        os.system('cls')
    return hours

有关清除线路的其他方法(从而避免os.system 调用,请参阅(如何)Print in one line dynamically。)

【讨论】:

  • @After_Sunset 如果您发现解决方案有帮助,您应该将其标记为您选择的答案,以便将来遇到类似问题的人轻松找到它
【解决方案2】:
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 # return outside the loop

【讨论】:

    【解决方案3】:

    return 语句没有正确缩进。它应该与 for 语句处于同一级别。

    【讨论】:

      【解决方案4】:
      weekday = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
      dayHourDictionary = {}
      
      for day in weekday:
         print "please enter the shift hours for", day ,":"
         shiftHours = input('')
         dayHourDictionary[day]=shiftHours
      
      
      
      print dayHourDictionary
      

      【讨论】:

      • 你能扩展一下你的答案吗?可能会添加一些 cmets?
      猜你喜欢
      • 1970-01-01
      • 2013-06-09
      • 2020-12-21
      • 2018-08-18
      • 1970-01-01
      • 2021-02-27
      • 1970-01-01
      • 2015-11-09
      • 2019-07-31
      相关资源
      最近更新 更多