I want the loop to break if True occurs. For some reason, the break statement get things twisted.
a = [[1,2,3], [4,5,6], [7,8,9], [1,4,7], [2,5,8], [3,6,9], [1,5,9], [7,5,3]]
b = [[9], [9, 7], [9, 7, 8], [9, 7, 8, 2]]
countdata = []
for x in range(len(b)):
for y in range(len(a)):
if all(elem in b[x] for elem in a[y]) == True:
break
countdata.append(all(elem in b[x] for elem in a[y]))
print(len(countdata))
Output:
>>>20
The output should be 18. Proof:
countdata = []
for x in range(len(b)):
for y in range(len(a)):
tt = all(elem in b[x] for elem in a[y] )
countdata.append(tt)
nylista = []
for z in countdata:
if z == True:
break
nylista.append(z)
print(len(nylista))
>>>18
Is it a bug?
You're break
ing the inner loop, but not the outer loop, so the outer loop continues, and then runs the inner loop again (which itself break
s when [7, 8, 9]
is contained in [9, 7, 8, 2]
).
There are a number of solutions for break
ing multiple loops for you to look at.
As stated here you are not breaking out of the external loop:
a = [[1,2,3], [4,5,6], [7,8,9], [1,4,7], [2,5,8], [3,6,9], [1,5,9], [7,5,3]]
b = [[9], [9, 7], [9, 7, 8], [9, 7, 8, 2]]
countdata = []
inner_break = False
for x in range(len(b)):
if inner_break:
break
for y in range(len(a)):
if all(elem in b[x] for elem in a[y]) == True:
inner_break = True
break
countdata.append(all(elem in b[x] for elem in a[y]))
print(len(countdata))
First, corrections in your code segment. The code segment you intend is
countdata = []
for x in range(len(b)):
for y in range(len(a)):
if all(elem in b[x] for elem in a[y]) == True:
break
countdata.append(all(elem in b[x] for elem in a[y]))
Next, when you encounter the break
statement you are exiting the inner loop only. Hence the difference in answers.
countdata = []
in_flag = False
for x in range(len(b)):
for y in range(len(a)):
if all(elem in b[x] for elem in a[y]) == True:
in_flag = True
break
countdata.append(all(elem in b[x] for elem in a[y]))
if in_flag:
break
This should fix it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.