打印不显示的值

时间:2017-05-29 02:17:22

标签: python output

我在Python中遇到了一个奇怪的问题。我有以下代码:

    for cd in self.current_charging_demands:
        print"EV{}".format(cd.id)

    # Check the value of SOC.
    for cd in self.current_charging_demands:
        print"EV{}, Current SOC: {}, required power: {}, allocated power: {}, max power: {}\n".format(cd.id, round(cd.battery.current_soc, 2), cd.battery.power_to_charge, cd.battery.allocated_powers, cd.battery.max_power)
        if round(cd.battery.current_soc, 2) >= cd.battery.desired_soc:
            #print"EV{} - current SOC: {}".format(cd.id, cd.battery.current_soc)
            result.append(cd)
            db.delete_charging_demand(self.current_charging_demands, cd.id)

第一个用于打印这些值:

EV1
EV2
EV5
EV4 

第二个是打印这些:

EV1, Current SOC: 0.44, required power: 15.1, allocated power: 0.15638636639, max power: 3.3

EV2, Current SOC: 0.9, required power: 1.0, allocated power: 1.0, max power: 1.0

EV4, Current SOC: 0.92, required power: 6.5, allocated power: 3.3, max power: 3.3

如您所见,第二个中缺少一个值(EV5),我实在无法解释原因。 for在同一个对象上完成,该对象在两个循环之间尚未修改。在下次调用这些函数时,我得到以下值:

EV1
EV5
EV4

表示第一个循环并且:

EV1, Current SOC: 0.44, required power: 15.0, allocated power: 0.15638636639, max power: 3.3

EV5, Current SOC: 0.35, required power: 23.7, allocated power: 0.0, max power: 3.3

EV4, Current SOC: 0.92, required power: 3.2, allocated power: 0.0, max power: 3.2

有关正在发生的事情的任何想法吗?

非常感谢。

1 个答案:

答案 0 :(得分:3)

在您的代码中有一行

db.delete_charging_demand(self.current_charging_demands, cd.id)

在迭代期间删除元素时应该非常小心。可能会跳过某些元素。

要查看此内容,请尝试运行以下代码。

a = [1, 2, 3, 4]
for x in a:
    print(x)
    if x == 2:
        a.remove(x)

它将打印出1 2 4,并且缺少3个。

要解决此问题,您可以看到this post