首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >值不被打印显示

值不被打印显示
EN

Stack Overflow用户
提问于 2017-05-29 02:17:21
回答 1查看 33关注 0票数 0

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

代码语言:javascript
复制
    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)

第一个用于打印这些值:

代码语言:javascript
复制
EV1
EV2
EV5
EV4 

第二种是打印这些:

代码语言:javascript
复制
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是在同一个对象上完成的,这两个循环之间都没有修改。在这些函数的下一个调用中,我将得到以下值:

代码语言:javascript
复制
EV1
EV5
EV4

用于第一个循环,并:

代码语言:javascript
复制
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

知道发生了什么吗?

非常感谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-29 02:23:29

在您的代码中有一行

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

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

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

代码语言:javascript
复制
a = [1, 2, 3, 4]
for x in a:
    print(x)
    if x == 2:
        a.remove(x)

它会打印出12,4,3是失踪的。

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44233814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档