Sorted one list as an other list

how can i sort one list with the same sort of an another… i make like this:

dim=[5,98,56]
dir=['a','c','b']
for i in range (0,len(dim):
    dimdir.append([dim[i],dir[i]])
sorted_dimdir=sorted(dimdir, key=lambda dimdir: dimdir[0])
dim=[]
dir=[]
for i in range (0,len(dimdir)):
    dim.append(dimdir[i][0])
    dir.append(dimdir[i][1])

but i think there is easier…

Maybe this?

dim=[5,98,56]
dir=['a','c','b']

comb=zip(dim,dir)
comb.sort() #sorts by first element, i.e. dim
dim_sorted,dir_sorted=zip(*comb)
1 Like

ok and to extract the index of the min value in a list?

Bunch of ways I guess, here is one that builds on my first example:

dim=[5,98,56,2,86]
dir=['b','e','c','a','d']
indices=list(range(len(dim)))

comb=zip(dim,dir,indices)
comb.sort()
dim_sorted,dir_sorted,indices_sorted=zip(*comb)
min_index=indices_sorted[0]

Don’t know how really ‘pythonic’ all that is though…

dim=[5,98,56,2,86]
dir=['b','e','c','a','d']
min_index = dim.index(min(dim))
print dir[min_index]

‘a’

2 Likes