【问题标题】:Adding a for loop to the list在列表中添加一个 for 循环
【发布时间】:2015-01-29 19:03:15
【问题描述】:

这是 Python 书中的问题:

设计一个程序,要求用户输入商店一周中每一天的销售额。金额应存储在列表中。使用循环计算一周的总销售额并显示结果。

这是我目前在 Python 代码中的内容:

Sunday = int(input("Enter the store sales for Sunday: "))
Monday = int(input("Enter the store sales for Monday: "))
Tuesday = int(input("Enter the store sales for Tuesday: "))
Wednsday = int(input("Enter the store sales for Wednsday: "))
Thursday = int(input("Enter the store sales for Thursday: "))
Friday = int(input("Enter the store sales for Friday: "))
Saturday = int(input("Enter the store sales for Saturday: "))

store_week_sales = [Sunday, Monday, Tuesday, Wednsday, Thursday, Friday, Saturday]

index = 0

我不太确定如何添加循环以便计算一周的总销售额。非常感谢您的帮助。

【问题讨论】:

  • 与问题没有直接关系的事情:你可以做sales = [int(input('Enter store sales for %s: ' % day)) for day in ['Sunday', 'Monday', 'Tuesday', 'Wednesday']]

标签: python list loops for-loop


【解决方案1】:

试试这个:

total = 0

for store_sale in store_week_sales:
    total += store_sale

print "Total week sales: %.2f" % total

Python 在 for 和(不存在的)foreach 之间没有区别,因为 for 已经迭代了可迭代的元素,而不是索引号。

【讨论】:

    【解决方案2】:

    如果你绝对想用 for 循环来做,它可以像 heltonbiker 描述。或者,您可以使用函数 sum 来完成。

    sumOfList = sum(store_week_sales);
    

    由于它是一个 for 循环的练习,这可能不是您这次要寻找的内容,但了解一下以供将来参考可能会很好。

    【讨论】:

      【解决方案3】:
      def main():
      
          total = 0.0
          daily_sales = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
          index = 0
      
          days_of_the_week = ['Sunday', 'Monday', 'Tuesday', 'Wednsday', 'Thursday', 'Friday', 'Saturday']
      
          for index in range(7):
      
              print("Enter the amount of sales for", days_of_the_week[index])
              daily_sales[index] = float(input("Enter the sales here: "))
      
              total += daily_sales[index]
      
          print("The total sales for the week is $", format(total, '.2f'), sep = ' ')
      
      main()
      

      【讨论】:

      • 请添加一些叙述来解释您倾倒给我们的这段代码的作用以及如何/为什么。
      猜你喜欢
      • 1970-01-01
      • 2019-08-13
      • 2023-03-12
      • 2020-03-23
      • 2022-01-06
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多