Python:在for循环中“突破”if语句

8
我理解在if语句中无法“打断”,只能从循环中跳出,然而我试图在for循环内部的if语句找到第一个“true”后概念上停止其继续执行。
# Import XML Parser
import xml.etree.ElementTree as ET

# Parse XML directly from the file path
tree = ET.parse('xml file')

# Create iterable item list
items = tree.findall('item')

# Create class for historic variables
class DataPoint:
    def __init__(self, low, high, freq):
        self.low = low
        self.high = high
        self.freq = freq

# Create Master Dictionary and variable list for historic variables
masterDictionary = {}

# Loop to assign variables as dictionary keys and associate their values with them
for item in items:
    thisKey = item.find('variable').text
    thisList = []
    masterDictionary[thisKey] = thisList

for item in items:
    thisKey = item.find('variable').text
    newDataPoint = DataPoint(float(item.find('low').text), float(item.find('high').text), float(item.find('freq').text))
    masterDictionary[thisKey].append(newDataPoint)

diceDictionary = {}
import random
for thisKey in masterDictionary.keys():
    randomValue = random.random()
    diceList = []
    thisList = []
    diceList = masterDictionary[thisKey]
    diceDictionary[thisKey] = thisList
    for i in range(len(diceList)):
        if randomValue <= sum(i.freq for i in diceList[0:i+1]):         
            print 'O', i, 'randomValue', randomValue, 'prob container', sum(i.freq for i in diceList[0:i+1])
            #diceRoll = random.uniform(diceList[i].low, diceList[i].high)
            #diceDictionary[thisKey].append(diceRoll)
        else:
            print 'X', i, 'randomValue', randomValue, 'prob container', sum(i.freq for i in diceList[0:i+1])

主字典中有两个键,每个键分别包含27个和29个数据点的列表。因此,循环

for i in range(len(diceList)):

将会对每个键运行i从0-26和0-28。这很好,但问题在于当if语句被评估时,一旦找到它,它随后将对所有以下范围项目为真。以下是打印输出:

X 0 randomValue 0.0775612781213 prob container 0.0294117647059
X 1 randomValue 0.0775612781213 prob container 0.0294117647059
X 2 randomValue 0.0775612781213 prob container 0.0294117647059
X 3 randomValue 0.0775612781213 prob container 0.0294117647059
O 4 randomValue 0.0775612781213 prob container 0.147058823529
O 5 randomValue 0.0775612781213 prob container 0.235294117647
O 6 randomValue 0.0775612781213 prob container 0.441176470588
O 7 randomValue 0.0775612781213 prob container 0.588235294118
O 8 randomValue 0.0775612781213 prob container 0.676470588235
O 9 randomValue 0.0775612781213 prob container 0.764705882353
O 10 randomValue 0.0775612781213 prob container 0.794117647059
O 11 randomValue 0.0775612781213 prob container 0.823529411765
O 12 randomValue 0.0775612781213 prob container 0.823529411765
O 13 randomValue 0.0775612781213 prob container 0.852941176471
O 14 randomValue 0.0775612781213 prob container 0.882352941176
O 15 randomValue 0.0775612781213 prob container 0.882352941176
O 16 randomValue 0.0775612781213 prob container 0.911764705882
O 17 randomValue 0.0775612781213 prob container 0.911764705882
O 18 randomValue 0.0775612781213 prob container 0.911764705882
O 19 randomValue 0.0775612781213 prob container 0.911764705882
O 20 randomValue 0.0775612781213 prob container 0.911764705882
O 21 randomValue 0.0775612781213 prob container 0.941176470588
O 22 randomValue 0.0775612781213 prob container 0.941176470588
O 23 randomValue 0.0775612781213 prob container 0.970588235294
O 24 randomValue 0.0775612781213 prob container 0.970588235294
O 25 randomValue 0.0775612781213 prob container 0.970588235294
O 26 randomValue 0.0775612781213 prob container 0.970588235294
O 27 randomValue 0.0775612781213 prob container 0.970588235294
O 28 randomValue 0.0775612781213 prob container 1.0
X 0 randomValue 0.803308376497 prob container 0.0294117647059
X 1 randomValue 0.803308376497 prob container 0.0294117647059
X 2 randomValue 0.803308376497 prob container 0.0294117647059
X 3 randomValue 0.803308376497 prob container 0.0294117647059
X 4 randomValue 0.803308376497 prob container 0.0294117647059
X 5 randomValue 0.803308376497 prob container 0.0294117647059
X 6 randomValue 0.803308376497 prob container 0.0882352941176
X 7 randomValue 0.803308376497 prob container 0.0882352941176
X 8 randomValue 0.803308376497 prob container 0.0882352941176
X 9 randomValue 0.803308376497 prob container 0.117647058824
X 10 randomValue 0.803308376497 prob container 0.147058823529
X 11 randomValue 0.803308376497 prob container 0.205882352941
X 12 randomValue 0.803308376497 prob container 0.264705882353
X 13 randomValue 0.803308376497 prob container 0.294117647059
X 14 randomValue 0.803308376497 prob container 0.382352941176
X 15 randomValue 0.803308376497 prob container 0.441176470588
X 16 randomValue 0.803308376497 prob container 0.470588235294
X 17 randomValue 0.803308376497 prob container 0.470588235294
X 18 randomValue 0.803308376497 prob container 0.529411764706
X 19 randomValue 0.803308376497 prob container 0.588235294118
X 20 randomValue 0.803308376497 prob container 0.647058823529
X 21 randomValue 0.803308376497 prob container 0.764705882353
O 22 randomValue 0.803308376497 prob container 0.823529411765
O 23 randomValue 0.803308376497 prob container 0.882352941176
O 24 randomValue 0.803308376497 prob container 0.970588235294
O 25 randomValue 0.803308376497 prob container 0.970588235294
O 26 randomValue 0.803308376497 prob container 1.0

如果某处出现了“X”,则表示if语句为假,一旦出现“O”,由于prob容器的增大(最高可达1.0),其余语句将始终为真。

我正在寻找一种方法,在循环内告诉我的if语句一旦找到第一个真实语句就停止,然后写入字典,再继续外部循环。

任何帮助都将不胜感激!

更新:

diceDictionary = {}
x=0 
while x < 3:
    import random
    for thisKey in masterDictionary.keys():
        randomValue = random.random()
        diceList = []
        thisList = []
        diceList = masterDictionary[thisKey]
        diceDictionary[thisKey] = thisList
        for i in range(len(diceList)):
            if randomValue <= sum(i.freq for i in diceList[0:i+1]):         
                print 'O', thisKey, i, 'randomValue', randomValue, 'prob container', sum(i.freq for i in diceList[0:i+1])
                diceRoll = random.uniform(diceList[i].low, diceList[i].high)
                diceDictionary[thisKey].append(diceRoll)
                break
            else:
                print 'X', thisKey, i, 'randomValue', randomValue, 'prob container', sum(i.freq for i in diceList[0:i+1])
    x = x + 1
print diceDictionary

产生:

X inflation 0 randomValue 0.500605733928 prob container 0.0294117647059
X inflation 1 randomValue 0.500605733928 prob container 0.0294117647059
X inflation 2 randomValue 0.500605733928 prob container 0.0294117647059
X inflation 3 randomValue 0.500605733928 prob container 0.0294117647059
X inflation 4 randomValue 0.500605733928 prob container 0.147058823529
X inflation 5 randomValue 0.500605733928 prob container 0.235294117647
X inflation 6 randomValue 0.500605733928 prob container 0.441176470588
O inflation 7 randomValue 0.500605733928 prob container 0.588235294118
X stock 0 randomValue 0.392225720409 prob container 0.0294117647059
X stock 1 randomValue 0.392225720409 prob container 0.0294117647059
X stock 2 randomValue 0.392225720409 prob container 0.0294117647059
X stock 3 randomValue 0.392225720409 prob container 0.0294117647059
X stock 4 randomValue 0.392225720409 prob container 0.0294117647059
X stock 5 randomValue 0.392225720409 prob container 0.0294117647059
X stock 6 randomValue 0.392225720409 prob container 0.0882352941176
X stock 7 randomValue 0.392225720409 prob container 0.0882352941176
X stock 8 randomValue 0.392225720409 prob container 0.0882352941176
X stock 9 randomValue 0.392225720409 prob container 0.117647058824
X stock 10 randomValue 0.392225720409 prob container 0.147058823529
X stock 11 randomValue 0.392225720409 prob container 0.205882352941
X stock 12 randomValue 0.392225720409 prob container 0.264705882353
X stock 13 randomValue 0.392225720409 prob container 0.294117647059
X stock 14 randomValue 0.392225720409 prob container 0.382352941176
O stock 15 randomValue 0.392225720409 prob container 0.441176470588
X inflation 0 randomValue 0.146182475695 prob container 0.0294117647059
X inflation 1 randomValue 0.146182475695 prob container 0.0294117647059
X inflation 2 randomValue 0.146182475695 prob container 0.0294117647059
X inflation 3 randomValue 0.146182475695 prob container 0.0294117647059
O inflation 4 randomValue 0.146182475695 prob container 0.147058823529
X stock 0 randomValue 0.745100497977 prob container 0.0294117647059
X stock 1 randomValue 0.745100497977 prob container 0.0294117647059
X stock 2 randomValue 0.745100497977 prob container 0.0294117647059
X stock 3 randomValue 0.745100497977 prob container 0.0294117647059
X stock 4 randomValue 0.745100497977 prob container 0.0294117647059
X stock 5 randomValue 0.745100497977 prob container 0.0294117647059
X stock 6 randomValue 0.745100497977 prob container 0.0882352941176
X stock 7 randomValue 0.745100497977 prob container 0.0882352941176
X stock 8 randomValue 0.745100497977 prob container 0.0882352941176
X stock 9 randomValue 0.745100497977 prob container 0.117647058824
X stock 10 randomValue 0.745100497977 prob container 0.147058823529
X stock 11 randomValue 0.745100497977 prob container 0.205882352941
X stock 12 randomValue 0.745100497977 prob container 0.264705882353
X stock 13 randomValue 0.745100497977 prob container 0.294117647059
X stock 14 randomValue 0.745100497977 prob container 0.382352941176
X stock 15 randomValue 0.745100497977 prob container 0.441176470588
X stock 16 randomValue 0.745100497977 prob container 0.470588235294
X stock 17 randomValue 0.745100497977 prob container 0.470588235294
X stock 18 randomValue 0.745100497977 prob container 0.529411764706
X stock 19 randomValue 0.745100497977 prob container 0.588235294118
X stock 20 randomValue 0.745100497977 prob container 0.647058823529
O stock 21 randomValue 0.745100497977 prob container 0.764705882353
X inflation 0 randomValue 0.332170052306 prob container 0.0294117647059
X inflation 1 randomValue 0.332170052306 prob container 0.0294117647059
X inflation 2 randomValue 0.332170052306 prob container 0.0294117647059
X inflation 3 randomValue 0.332170052306 prob container 0.0294117647059
X inflation 4 randomValue 0.332170052306 prob container 0.147058823529
X inflation 5 randomValue 0.332170052306 prob container 0.235294117647
O inflation 6 randomValue 0.332170052306 prob container 0.441176470588
X stock 0 randomValue 0.145551106438 prob container 0.0294117647059
X stock 1 randomValue 0.145551106438 prob container 0.0294117647059
X stock 2 randomValue 0.145551106438 prob container 0.0294117647059
X stock 3 randomValue 0.145551106438 prob container 0.0294117647059
X stock 4 randomValue 0.145551106438 prob container 0.0294117647059
X stock 5 randomValue 0.145551106438 prob container 0.0294117647059
X stock 6 randomValue 0.145551106438 prob container 0.0882352941176
X stock 7 randomValue 0.145551106438 prob container 0.0882352941176
X stock 8 randomValue 0.145551106438 prob container 0.0882352941176
X stock 9 randomValue 0.145551106438 prob container 0.117647058824
O stock 10 randomValue 0.145551106438 prob container 0.147058823529
{'inflation': [0.028073642645577577], 'stock': [-0.07388514885974767]}
5个回答

12
    if randomValue <= sum(i.freq for i in diceList[0:i+1]):         
        print 'O', i, 'randomValue', randomValue, 'prob container', sum(i.freq for i in diceList[0:i+1])
        break

Break可以终止“最近的封闭循环,如果该循环有else子句,则跳过该子句”。外部循环将继续下一次迭代。所以你不是“打破了if语句”,而是打破了包含它的循环。在使用break之前,您只需要将diceList [0:i + 1]diceList [0:len(diceList)+ 1]中的所有值设置为true。


我按照你最初的建议尝试了break,它确实起作用(请参见上面的更新),但是我似乎无法在循环中将所选值附加到字典列表中(请注意while循环的添加)。每个键列表中应该有3个值,但是正如您所看到的,只有最后一次迭代显示出来。我似乎在每次通过时都在覆盖而不是附加。有什么想法吗? - indigo
面向对象编程,没事了。我把这个列表移到循环外面,就不会被覆盖了。是我的疏忽。谢谢! - indigo

2

一种方法是在内部代码中引发异常,在for循环内捕获并继续循环。


1

那么您知道该语句是真实的条件是什么?我认为这可能是“如果最后一个语句是真实的”,但在您的示例输出中,最终回到了 False ?

无论如何,考虑将此作为某种第一条件添加到您的if中:

if (you don't already know it's True) and (the condition you currently evaluate):
    <Do calculations>

如果第一部分被评估为False(即您已经知道它是True),Python不应该评估and的第二个术语(因为它现在不能是True)并继续执行。您只需要添加另一个else子句(因此可能使else成为elif),并在那里处理它。

NB:这种方法可能有点hacky,具体取决于您需要做什么来确定您是否已经知道该语句是True :\


0

如果你确定想要跳出 if 语句的代码块,并且只有 "break" 可以实现,那么你可以在希望跳出的位置加上 "break",然后将整个 if 语句块放在一个只执行一次的循环中。


0
从我的理解来看,您正在尝试将if比较保存到循环的其余部分。我认为您需要将当前的循环拆分成两个循环,一个执行if语句并找到分区点,另一个仅跳过比较。您可以将当前正在处理的i保留在循环外的变量中,然后在第二个循环中从该点继续执行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接