首页 > 解决方案 > 如何遍历元组列表?

问题描述

我对这个关于python的作业有一些疑问。练习包括以下内容:

这辆公共汽车有一个乘客出入控制系统来监控它所载的乘客数量,从而检测何时容量过高。

在每一站,乘客的进出都由一个由两个整数组成的元组表示。

bus_stop = (in, out)

停止的连续性由这些元组的列表表示。

stops = [(in1, out1), (in2, out2), (in3, out3), (in4, out4)]

目标:

  • 使用列表、元组
  • 使用 while/for 循环
  • 使用最小、最大、长度
  • 使用平均值、标准差

任务:

  • 计算停靠点的数量。
  • 为变量分配一个列表,其元素是每个停靠站(进出)的乘客数量,
  • 找到总线的最大占用。

到目前为止,我已经提出了这段代码,但它没有返回任何东西,所以,由于我对 python 的缺乏经验,我肯定做错了什么。

bus_is_full = False
bus_capacity = 0
stops = [(20, 0), (13, 7), (40, 10), (1, 20)]
while not bus_is_full == True:
    for stop in stops:
        bus_capacity = stops()
        if bus_capacity == 50:
            bus_is_full = True
            stops +=1 
        elif bus_capacity < 50:
            stops +=1
    print(bus_capacity)

标签: pythonwhile-looptuplesiteration

解决方案


您可以将元组转换为列表。

    bus_is_full = False
    bus_capacity = 0
    stops = [(20, 0), (13, 7), (40, 10), (1, 20)]
    number_stops = len(stops)
    print("The number of stops is : {0}\n".format(bus_capacity))
    i=0
    while i < number_stops :
        for stop in stops:
            l = list(stop)
            in_i = l[0]
            out_i = l[1]
            print("For the {0} stop, {1} passengers entered and {2} passengers left the bus".format(i, in_i, out_i) )
            i += 1

推荐阅读