-2

For example, I have 2 lists, X and Y:

X = [1, 2, 3, 4, 5]
Y = ["A", "B", "C", "D", "E"]

I want to pair the values up so that A corresponds with 1, B with 2 and so on so that if I put one list in a certain order, the other one will follow that order

For example, if I order list X from highest to lowest (54321) and print it, then print list Y, list Y will print in the order (EDCBA)

kederrac
  • 16,819
  • 6
  • 32
  • 55
  • You are looking for `zip`. – Ch3steR Feb 07 '20 at 13:35
  • `list(zip(Y, X))`…? Then they are truly paired and you can manipulate them as pairs. – deceze Feb 07 '20 at 13:35
  • You can construct a list of pairs that fixes the ordering, and you can use one list in constructing the `key` function for sorting the other, but you cannot link the lists so that reordering one automatically reorders the other. – chepner Feb 07 '20 at 13:36
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – brainkz Feb 07 '20 at 13:37

3 Answers3

1

I changed your lists for an example :

X = ["a", "b" , "c" , "d" , "e" , "f" ]
Y = [56, 23, 43, 97, 43, 102]
z = zip(X, Y)

# if you want to sort by numbers in Y :
res = sorted(z, key = lambda val: val[1]) 
print(res) 
# [('b', 23), ('c', 43), ('e', 43), ('a', 56), ('d', 97), ('f', 102)]
Phoenixo
  • 2,071
  • 1
  • 6
  • 13
0

You can try this:-

X = [1, 2, 3, 4, 5]
Y = ["A", "B", "C", "D", "E"]
print(dict(zip(X,Y)))
Vaibhav Jadhav
  • 2,020
  • 1
  • 7
  • 20
  • That doesn't appear to be what the OP is asking. They seem to want something like `X.sort(reverse=True)` and have that automatically make `Y` reversed as well. – chepner Feb 07 '20 at 13:38
  • @chepner What OP is asking for and what the realistic solution is are sometimes different things… – deceze Feb 07 '20 at 13:41
  • Yes, but that doesn't necessarily mean the answer to the question is "do the feasible thing". Sometimes, the answer is "you can't do that". – chepner Feb 07 '20 at 14:12
0

to pair your lists you can use the built-in function zip:

list(zip(X, Y))

then you can sort them:

new_list = list(zip(X, Y))
new_list.sort(reverse=True)

print(new_list)

output:

[(5, 'E'), (4, 'D'), (3, 'C'), (2, 'B'), (1, 'A')]
kederrac
  • 16,819
  • 6
  • 32
  • 55