-1

I have a list containing numbers and one containing users. The first element of the first list belongs to the first element of the second list and so on. I then want to sort the number list using sort() and want the usernames to still match with the numbers they had before.

from:

users = ["max", "david", "freddy"]

numbers = [9, 3, 10]

to:

users = ["david", "max", "freddy"]

numbers = [3, 9, 10]
Celltox
  • 127
  • 8
  • Why not just use a dict (key value pair) to map these numbers to users? – plum 0 Dec 29 '20 at 15:31
  • Does this answer your question? [How to sort two lists (which reference each other) in the exact same way](https://stackoverflow.com/questions/9764298/how-to-sort-two-lists-which-reference-each-other-in-the-exact-same-way) – Georgy Dec 30 '20 at 15:00

5 Answers5

2

You could use a list comprehension along with zip and sorted:

>>> users = ["max", "david", "Freddy"]
>>> numbers = [9, 3, 10]
>>> sorted_users = [u for _, u in sorted(zip(numbers, users)]
>>> sorted_users
['david', 'max', 'freddy']
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

I would suggest grouping your values together in a list of tuples or dictionaries:

data = [
    ('max',    9),
    ('david',  3),
    ('freddy', 10)
]

and then you can use custom sorting to sort this list:

data.sort(key=lambda x: x[1])

This way your data is stored in a way which keeps their relationship.

To use dictionaries instead requires this simple change:

data = [
    {'name': 'max',    'number': 9},
    {'name': 'david',  'number': 3},
    {'name': 'freddy', 'number': 10}
]

and then change your sort code to

data.sort(key=lambda x: x['number'])
dwb
  • 2,136
  • 13
  • 27
1

You can zip the two into one list, sort based on the number, then unzip them:

users = ["max", "david", "freddy"]
numbers = [9, 3, 10]

zipped = sorted(zip(numbers, users), key=lambda x: x[0])

numbers, users = zip(*zipped)
Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

You could try a dictionary for user numbers and user names

users = ["max", "david", "freddy"]

numbers = [9, 3, 10]

dictionary = {users[i]: numbers[i] for i in range(len(numbers))} 

{'max': 9, 'david': 3, 'freddy': 10}

and then sort the dictionary and convert back to lists. \

nsh1998
  • 106
  • 9
0

Using the right combination of zip and map, you can do this in one line:

users   = ["max", "david", "freddy"]
numbers = [9, 3, 10]

numbers,users = map(list,zip(*sorted(zip(numbers,users))))

print(users)   # ['david', 'max', 'freddy'] 
print(numbers) # [3, 9, 10]
Alain T.
  • 40,517
  • 4
  • 31
  • 51