1

Sorting two lists (a, b) according to a and returning back two sorted lists separately as exactly done below is correct.

a = ['apple','carrot','banana']
b = [5,10,15]

s = sorted(zip(a,b))
a,b = map(list, zip(*s))

print a
print b

['apple', 'banana', 'carrot']
[5, 15, 10]

But, any better ways to do this? Given condition: Two lists, a and b. Result: As printed above

PS This is Python 2.7

1 Answer 1

1

I would do it this way because I have an aversion to map, but it isn't obviously superior to your way. My reason is simply that list comprehensions are readily understood by most Python programmers, but functional programming concepts less so, since the language isn't really set up for functional programming.

In [6]: a = ['apple','carrot','banana']

In [7]: b = [5,10,15]

In [8]: A, B = (list(e) for e in zip(*sorted(zip(a,b))))

In [9]: A
Out[9]: ['apple', 'banana', 'carrot']

In [10]: B
Out[10]: [5, 15, 10]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.