Reputation: 123
I am looking for simple way to sort 2 lists at once. I need to sort first list containing strings by alphabet a same way sort second list containing integers. Data of lists are related (first[1] is related with second[1] ... ). So I need to keep same index for the pair with same index from both lists. For example:
first = ["B","C","D","A"]
second = [2,3,4,1]
I would like to sort it like this:
first = ["A","B","C","D"]
second = [1,2,3,4]
I am not sure if is it even possible to do that simple way.
Upvotes: 0
Views: 99
Reputation: 2492
or you could use dicts:
>>> d = {"B":2,"C":3,"D":4,"A":1}
>>> sorted(d)
['A', 'B', 'C', 'D']
>>> d["A"]
1
>>> d["C"]
3
>>> for i in sorted(d):
print(d[i])
1
2
3
4
Upvotes: 0
Reputation: 189
try to using tuple visit wiki.python.org ex:
>>> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
output
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Upvotes: 0
Reputation: 473873
You can zip()
them, sort and then unzip (though I don't fully understand the use case):
>>> first = ["B","C","D","A"]
>>> second = [2,3,4,1]
>>>
>>> zip(first, second)
[('B', 2), ('C', 3), ('D', 4), ('A', 1)]
>>> first_new, second_new = zip(*sorted(zip(first, second)))
>>> first_new
('A', 'B', 'C', 'D')
>>> second_new
(1, 2, 3, 4)
Upvotes: 2