I have started learning about lambda functions in python and I like the power it has, but I have hit a wall with using if/else with a for loop in a lambda.
I know I can use the following:
def compare(value, compare_value):
if value < compare_value:
return [value, True]
else:
return [value, False]
number_list = [0, 1, 2, 3]
compare_number = 2
print [compare(number, compare_number) for number in number_list]
This I know will print:
[[0, True], [1, True], [2, False], [3, False]]
I also know I can get the same printout using this:
compare = lambda value, compare_value: [value, True] if value < compare_value else [value, False]
number_list = [0, 1, 2, 3]
compare_number = 2
print [compare(number, compare_number) for number in number_list]
I want to know if I can put all the iteration and comparison in one line. I tried the code below, python doesn't like it.
number_list = [0, 1, 2, 3]
compare_number = 2
print [[number, True] for number in number_list if number < compare_number else [number, False]]
Aucun commentaire:
Enregistrer un commentaire