I have a list of strings like this:
X = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ]
The most obvious solution to me is to use the key
keyword arg.
>>> X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
>>> Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
>>> keydict = dict(zip(X, Y))
>>> X.sort(key=keydict.get)
>>> X
['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
Note that you can shorten this to a one-liner if you care to:
>>> X.sort(key=dict(zip(X, Y)).get)
more_itertools has a tool for sorting iterables in parallel:
Given
from more_itertools import sort_together
X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
Demo
sort_together([Y, X])[1]
# ('a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g')
list1 = ['a','b','c','d','e','f','g','h','i']
list2 = [0,1,1,0,1,2,2,0,1]
output=[]
cur_loclist = []
To get unique values present in list2
list_set = set(list2)
To find the loc of the index in list2
list_str = ''.join(str(s) for s in list2)
Location of index in list2
is tracked using cur_loclist
[0, 3, 7, 1, 2, 4, 8, 5, 6]
for i in list_set:
cur_loc = list_str.find(str(i))
while cur_loc >= 0:
cur_loclist.append(cur_loc)
cur_loc = list_str.find(str(i),cur_loc+1)
print(cur_loclist)
for i in range(0,len(cur_loclist)):
output.append(list1[cur_loclist[i]])
print(output)