-3

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])
大陸北方網友
  • 3,696
  • 3
  • 12
  • 37
Omat
  • 67
  • 1
  • 1
  • 4

2 Answers2

0

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.

deepyaman
  • 538
  • 5
  • 16
0
  • Use zip to pair up items in corresponding positions. (This will produce an iterable, so either convert to list or use sorted rather than .sort.)
  • To reverse the order, either use -x[1] as the key, or pass reverse=True.
  • (typo) Name the position variable consistently.
  • (style) Avoid using 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)
Jiří Baum
  • 6,697
  • 2
  • 17
  • 17