gpt4 book ai didi

python - 在跳过值的同时遍历 python 中的列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:40:09 25 4
gpt4 key购买 nike

我有一个数字列表,我想遍历所有列表并进行以下计算。

这些值中的每一个都添加到负载需求并从可用功率中减去。我的代码迭代到某个点并停止计算。

num = [5,2,1,2,8,1,2]

Pa = 130 #available power
Ld = 100 #total load demad
Pn = 0 #new power request
node =0

for number in num:
Pa -= num[node]
Ld += num[node]
if Pa >= Ld:
Pna = Pa
Lnd = Ld
Pn += num[node]

#print "new added value is : ", Pn
node += 1

print "Available power : ", Pna
print "Demand power : ", Lnd

输出是

Available power :  120
Demand power : 110

迭代到第 5 个元素并停止,我想从第 6 个元素开始迭代,同时跳过 Pa >= Ld 变为 false 的值。

我是 Python 新手,所以我的编码结构可能不太好。有没有办法使用 forif 循环或其他方法来满足我的要求?

提前致谢

最佳答案

在验证当前节点值可接受之前,不应修改 PaLd

num = [5, 2, 1, 2, 8, 1, 2]

Pa = 130 #available power
Ld = 100 #total load demad
Pn = 0 #new power request

for node in num:
temp_Pa = Pa - node
temp_Ld = Ld + node
if temp_Pa >= temp_Ld:
Pa = temp_Pa
Ld = temp_Ld
Pn += node
print(node, 'ok', Pn, Pa, Ld)
else:
print('skipping', node)

print("Available power : ", Pa)
print("Demand power : ", Ld)

输出

5 ok 5 125 105
2 ok 7 123 107
1 ok 8 122 108
2 ok 10 120 110
skipping 8
1 ok 11 119 111
2 ok 13 117 113
Available power : 117
Demand power : 113

关于python - 在跳过值的同时遍历 python 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45532881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com