For循环-不能遍历元素



问题:该函数的for循环不是遍历所有元素。它停在1点。我使用了一些诊断打印语句来计算循环的数量,并在1处停止。我已经检查了标识和循环,但似乎找不到问题。

def process_data(data):
"""Analyzes the data, looking for maximums.
Returns a list of lines that summarize the information.
"""
loop_count = 0
year_by_sales = dict()
max_revenue = {"revenue": 0}
# ----------->This is where the Loop Issue Exists <-----
for item in data:
item_price = locale.atof(item["price"].strip("$"))
item_revenue = item["total_sales"] * item_price
if item["car"]["car_year"] not in year_by_sales.keys():
year_by_sales[item["car"]["car_year"]] = item["total_sales"]
loop_count += 1
if item_revenue > max_revenue["revenue"]:
item["revenue"] = item_revenue
max_revenue = item
most_sold_model = item['car']['car_model']
highest_total_sales = item["total_sales"]
else:
year_by_sales[item["car"]["car_year"]] += item["total_sales"]
loop_count +=1 
most_popular_year = max(year_by_sales, key=year_by_sales.get)
summary = [
"The {} generated the most revenue: ${}".format(
format_car(max_revenue["car"]), max_revenue["revenue"]
),
f"The {most_sold_model} had the most sales: {highest_total_sales}",
f"The most popular year was {most_popular_year} with {highest_total_sales} sales.",
]
print(loop_count)
print(year_by_sales)
return summary
<标题>输入数据
[{
"id": 1,
"car": {
"car_make": "Ford",
"car_model": "Club Wagon",
"car_year": 1997
},
"price": "$5179.39",
"total_sales": 446
},
{
"id": 2,
"car": {
"car_make": "Acura",
"car_model": "TL",
"car_year": 2005
},
"price": "$14558.19",
"total_sales": 589
},
{
"id": 3,
"car": {
"car_make": "Volkswagen",
"car_model": "Jetta",
"car_year": 2009
},
"price": "$14879.11",
"total_sales": 825
}]

这个脚本的整个代码库是https://replit.com/join/dkuzpdujne-terry-brooksjr

实际上问题是你的return语句在for循环中,所以你在第一次迭代之后返回,如果你把它移到下面这样的地方,它应该运行得很好:

def process_data(data):
"""Analyzes the data, looking for maximums.
Returns a list of lines that summarize the information.
"""
loop_count = 0
year_by_sales = dict()
max_revenue = {"revenue": 0}
# ----------->This is where the Loop Issue Exists <-----
for item in data:
item_price = locale.atof(item["price"].strip("$"))
item_revenue = item["total_sales"] * item_price
if item["car"]["car_year"] not in year_by_sales.keys():
year_by_sales[item["car"]["car_year"]] = item["total_sales"]
loop_count += 1
if item_revenue > max_revenue["revenue"]:
item["revenue"] = item_revenue
max_revenue = item
most_sold_model = item['car']['car_model']
highest_total_sales = item["total_sales"]
else:
year_by_sales[item["car"]["car_year"]] += item["total_sales"]
loop_count +=1 
most_popular_year = max(year_by_sales, key=year_by_sales.get)
summary = "1"
print(loop_count)
print(year_by_sales)
return summary # move this out of for loop

相关内容

  • 没有找到相关文章

最新更新