首页 > 解决方案 > 使用 namedtuple 变量创建一个新列表,并在模拟运行时对其进行迭代?

问题描述

我已经建立了一个充电模拟程序(完美运行!),当我运行模拟时,它会打印出关于特定充电站发生的事情的实时信息(有多少汽车在充电,有多少在排队等)

现在我想保存这些信息,这样我就可以用它来创建一个 CSV 文件,而且正如我所注意到的,这里有很多选项。

我目前正在尝试命名元组,效果很好。

这是那个小片段的代码:

        hotspot_record = namedtuple("hotspot_day_info", ('hour', 'name', 'cars_in_queue', 'rejected_cars', 'bailed_cars','count_queue_per_hour_and_avg'))
        hotspot_stats_per_hours.append(hotspot_record(
        hour=hour,
        name=hotspot.station_name,
        cars_in_queue=len(hotspot.cars_waiting_in_queue),
        rejected_cars=hotspot.rejected_cars,
        bailed_cars=hotspot.bailed_cars,
        count_queue_per_hour_and_avg = []))  # How can i add cars per hour here and then divide by 24?

所以现在这很好用,但我希望能够在最后一个变量“count_queue_per_hour_and_avg”列表中对从 1 小时到 24 小时的队列长度求和。

这可能吗?我该怎么做?如果没有,你有什么建议?

在下面,您可以看到它是如何在终端中打印的:

hotspot_day_info(hour=24, name='station1', cars_in_queue=20, rejected_cars=7076, bailed_cars=704, count_queue_per_hour_and_avg=[])
----------------------
hotspot_day_info(hour=24, name='station2', cars_in_queue=10, rejected_cars=2258, bailed_cars=606, count_queue_per_hour_and_avg=[])
----------------------
hotspot_day_info(hour=24, name='station3', cars_in_queue=20, rejected_cars=3408, bailed_cars=309, count_queue_per_hour_and_avg=[])
----------------------
hotspot_day_info(hour=24, name='station4', cars_in_queue=20, rejected_cars=5100, bailed_cars=603, count_queue_per_hour_and_avg=[])
===============================================

所以你会在每一行的末尾看到列表是空的。但是我再次问是否可以将“cars_in_queue”值添加到其中并将所有值相加,最后除以 24 以找到每个车站的平均队列长度?

谢谢你。

标签: python

解决方案


推荐阅读