I am using a for-loop within another for-loop to iterate through and compare two data sets. I want to first use the inner for loop to check for a condition and then, if it fails, to print a value from the outer loop.
For example:
for (i) in list_one:
for (j) in list_two:
if (condition):
print(j)
if the condition for 'print(j)' fails for all instances in list_two, I want the current value of list_one to be printed. Something like an 'if: for:' statement seems like it would make sense but I'm not sure if those are possible in Python. Thanks for the help
You can just add a fail flag, like
for (i) in list_one:
fail = True
for (j) in list_two:
if (condition):
fail = False
print(j)
if fail:
print(i)
If you need to print only the first satisfy condition
and then break out of the loop, then you can use for... else
for (i) in list_one:
for (j) in list_two:
if (condition):
print(j)
break
else:
print(i)
If you want to print all the values which satisfy the condition
in inner loop, you can use one more variable
for (i) in list_one:
print_i = True
for (j) in list_two:
if (condition):
print(j)
print_i = False
if print_i:
print(i)
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.