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
-
can you share the output/error you are getting now?s510– s5102022年03月14日 06:53:40 +00:00Commented Mar 14, 2022 at 6:53
-
If the condition is true for some j, do you want to continue checking/printing the remaining js?Kelly Bundy– Kelly Bundy2022年03月14日 07:00:41 +00:00Commented Mar 14, 2022 at 7:00
2 Answers 2
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)
1 Comment
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)