Python Condition Statement with For-Loop
I am attempting to write a single line of Python code for the following:
is_valid = False
for single_object in object_list:
if single_object.test == test:
is_valid = True
if not is_valid:
return 'Bad data!'
I know that there has to be a way to accomplish this 开发者_StackOverflowin less code. I mean, it's Python!
is_valid = any(o.test == test for o in object_list)
The any(iterable)
function returns True
if any of the values in iterable
are True
, and False
if none of them are. I'm using a "generator expression" to go through the values in object_list
and evaluate the condition.
Less code is often not better code.
for single_object in object_list:
if single_object.test == test:
break
else:
return 'Bad data!'
While this is not one line of code, it is less, cleaner code, and is arguably easier to read than any
. It's also basically the same speed.
The else
clause on a loop only executes if the loop wasn't exited by a break
statement.
I think this is just as Pythonic as the one line solution.
@Jeremy Banks's solution seems to be perfect to me. Nevertheless I would like to present another one. Not in order to be even superior (it is not), but to show alternatives for non-boolean problems, or if it is important to get the very precise object in the list (maybe in order to modify or remove it).
valid_one = next((o.test for o in object_list if o.test == test), None)
if valid_one is None:
# not valid
else:
object_list.remove(valid_one)
# or
valid_one.special_atr = 42
精彩评论