+ 3
Lambda for list
How can i use lambda-function for compare every two elements of list? For ex. If All b[i]<=b[i+1] in list b , then true
3 odpowiedzi
+ 2
This uses a lambda to do what you're saying:
def is_sorted(l):
return all(map(lambda value_tuple : value_tuple[0] == 0 or value_tuple[1] >= l[value_tuple[0] - 1], enumerate(l)))
The list is enumerated so the lambda function is aware of what index it is looking at.
That enumerated list is mapped to bool such that the bool value is basically the meaning of "b[i]<=b[i+1]". Index 0 is special because there is no previous element to compare with. For that special case, True is returned.
Finally, the resulting list of True and False values are reduced to a single True or False value by calling "all". All elements in the list must be True for the result to be True.
Without using a lambda function, you could do this which is much shorter and simpler:
def is_sorted(l):
return all(l[i] <= l[i+1] for i in range(len(l)-1))
+ 2
Josh Greig i hoped by using lambda,i and j it will be short way. Where are i &j are indexes of list
+ 1
Yeah, I can't think of a shorter way to use a lambda function for this.
This is shorter than the previous answer but it probably isn't what you want since it operates on the list as a whole:
lamda l : all(l[i] <= l[i+1] for i in range(len(l)-1))