【问题标题】:For Loop - Failing to Iterate Over ElementsFor 循环 - 无法遍历元素
【发布时间】:2023-01-13 20:39:05
【问题描述】:

问题:此函数的 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

【问题讨论】:

  • 请描述作为第一个参数传递给您的函数的内容,即data实际上是什么
  • @Daweo - 添加了一个缩短的输入数据样本
  • 您将返回到 for 循环内。它永远没有机会第二次循环,因为函数返回了。
  • 您在第一次迭代结束时从函数返回。
  • @Mark 我刚刚注意到,我的大脑被炸了

标签: python for-loop iteration


【解决方案1】:

实际上问题是你的 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

【讨论】:

    猜你喜欢
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 2012-11-23
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多