我在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正如您所看到的,在第二个for中缺少一个值(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知道发生了什么吗?
非常感谢。
发布于 2017-05-29 02:23:29
在您的代码中有一行
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)它会打印出12,4,3是失踪的。
要解决这个问题,您可以看到this post。
https://stackoverflow.com/questions/44233814
复制相似问题