2017-05-29 63 views
0

我在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 

上正在发生的事情你知道吗?

非常感谢。

回答

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

+0

谢谢,它现在可行! – Ecterion