Need to sort a list of tuples by the last element, tuples can be empty. I know how to sort if tuples are not empty:
sorted(lst, key=lambda p: p[-1]);
But when list has ()
: IndexError: tuple index out of range
.
I couldn't find how to avoid it.
just check if the tuple
is empty before taking the last element.
sorted(lst, key=lambda p: bool(p) and p[-1])
bool(p) and p[-1]
returns False
(which evaluates to 0) when tuple is empty, otherwise it returns the last value.
With that approach, empty tuples come first in the sorted list if all values are positive. It needs more tuning to make them appear first or last in the generic case, still doable by returning a tuple
in the lambda:
sorted(lst, key=lambda p: (not bool(p),bool(p) and p[-1]))
the following will make the empty tuples come last in the list (because of the not
yielding True
when empty)
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.