Question

consider I have input list contains elements 19 14 36 how to assign a name to each element say A for 1st element, B for 2nd and C for 3rd and the output is sorted list ( 14, 19, 36) but the printed list on console I want it to be (B, A,C)

what is the function do assignment operation in python?

Was it helpful?

Solution

The easiest way to do this for an arbitrary length list would probably be something like:

from operator import itemgetter
from string import ascii_uppercase

data = [19, 14, 36]

labelled = zip(data, ascii_uppercase) # [(19, 'A'), (14, 'B'), (36, 'C')]

sorted_data = sorted(labelled, 
                     key=itemgetter(0)) # [(14, 'B'), (19, 'A'), (36, 'C')]

labels = [pair[1] for pair in sorted_data] # ['B', 'A', 'C']

OTHER TIPS

You can do it with zip:

>>> a = [19, 14, 36]
>>> b = ['A', 'B', 'C']

>>> print [b for (a,b) in sorted(zip(a,b), key=lambda x: x[0])]
['B', 'A', 'C']

You can experiment here

You can use zip and itemgetter to do the trick:

import operator
number_arr = [19, 14, 32]
letter_arr = ['A', 'B', 'C']

zipped = zip(number_arr, letter_arr)

sorted_by_number = sorted(zipped, key=operator.itemgetter(0))

print list(map(operator.itemgetter(1), sorted_by_number))

Refer to python docs on zip, map and itemgetter for details

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top