I will like to sort by position in descending order. Given:
name = ["Shawn", "Patrick", "Nancy", "Viola"]
position = [3,1,4,2]
l =[name,positions]
l.sort(key=lambda x: x[1])
I will like to sort by position in descending order. Given:
name = ["Shawn", "Patrick", "Nancy", "Viola"]
position = [3,1,4,2]
l =[name,positions]
l.sort(key=lambda x: x[1])
Change l = [name, positions]
to l = list(zip(name,position))
:
>>> name = ["Shawn", "Patrick", "Nancy", "Viola"]
>>> position = [3,1,4,2]
>>> l = list(zip(name,position))
>>> l.sort(key=lambda x: -x[1])
>>> l
[('Nancy', 4), ('Shawn', 3), ('Viola', 2), ('Patrick', 1)]
Also note the modified sort key for descending order.
zip
to pair up items in corresponding positions. (This will produce an iterable, so either convert to list or use sorted
rather than .sort
.)-x[1]
as the key, or pass reverse=True
.position
variable consistently.l
as a variable name, as it can be confused with 1
and I
.name = ["Shawn", "Patrick", "Nancy", "Viola"]
position = [3, 1, 4, 2]
l = zip(name, position)
l = sorted(l, key=lambda x: x[1], reverse=True)