0

I have two lists; say one of fruits and another of equal length but of unordered numbers:

eg:

Fruits = ['apple', 'banana', 'pineapple', 'kiwifruit'],
Numbers = [3, 2, 4, 1]

How can I firstly assign the number

  • 3 to apple,
  • 2 to banana,
  • 4 to pineapple and
  • 1 to kiwifruit

and secondly order them according to their new numbers?

i.e

sortedlist = ['kiwifruit', 'banana', 'apple', 'pineapple'].

My attempts so far have included the enumerate function and the sorted function, but I can't seem to assign and then sort.

5
  • 1
    The question has been answered for you, but you really should show some of you own code and attempts you've made already - this sounds like homework. Commented Dec 3, 2012 at 5:37
  • I did use the sorted function, but my attempts were quite far off from a good solution. Also, this isn't a homework question. Commented Dec 3, 2012 at 5:47
  • You've got a bird in your list of fruits! Commented Dec 3, 2012 at 5:50
  • @gnibbler on the off chance you aren't just joking, en.wikipedia.org/wiki/Kiwifruit Commented Dec 3, 2012 at 7:22
  • @KarlKnechtel, indeed :) It was originally "kiwi" there. As an expat Kiwi (person) it drives me nuts. Commented Dec 3, 2012 at 8:59

5 Answers 5

10
sortedlist = [x[1] for x in sorted(zip(Numbers, Fruits))]
Sign up to request clarification or add additional context in comments.

Comments

0

assignment can be done like this

In [25]: d = dict(zip(Numbers, Fruits))

In [26]: d
Out[26]: {1: 'kiwi', 2: 'banana', 3: 'apple', 4: 'pineapple'}

and then you can sort based on keys of the dictionary

In [27]: [d[i] for i in sorted(d.keys())]
Out[27]: ['kiwi', 'banana', 'apple', 'pineapple']

Comments

0

numpy is cool for this

import numpy as np
fruits = np.array(['apple', 'banana', 'pineapple', 'kiwi'])
sorted_list = fruits[[2, 1, 3, 0]] #note its 0 based indexing ...
print sorted_list

Comments

0

How about:

Fruits = ['apple', 'banana', 'pineapple', 'kiwi']
Numbers = [3, 2, 4, 1]

New_Fruits = [ Fruits[idx-1] for idx in Numbers ]

This only works since your index list (Numbers) is sequential integers. It would even be a little more clean if Numbers = [ 2, 1, 3, 0 ].

The advantage is that it avoids a call to zip, so it might be a little more efficient. The downside is that it is less general. You need to have an appropriate index list for it to work.

Comments

0
Fruits = ['apple', 'banana', 'pineapple', 'kiwifruit'],
Numbers = [3, 2, 4, 1]
new = []
for x in range(len(Numbers)):
    new.append([Fruits[x],Numbers[x]])
new.sort(key=lambda x: x[1])
final = []
for x in new:
     final.append(x[0])

Final is the final list

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.