Reverse list by values

Hello, can someone tell me how to sort a list by values but in reverse order? I do not want to reverse the entire list, but to reverse values inside the list, so an item with the highest value will switch place with the item with the lowest value, 2nd highest with 2nd lowest, and so on.

So, to be clear: from your example, what do you want the output to look like?

Can you maybe give some context to why you want to do this? Just Curious

1 Like

Thanks for the reply.

So I have to compare the highest and the lowest values in the list and switch their places in the list. So in this example the highest value is 92 at index 6, and it has to change place with the lowest value number 4 at index 3, and so on. This should be the end result

1 2

you can use dictionary to do mapping, but i believe there are more effective ways than using dictionary that i do not know off.

olddata = [15,7,13,4,11,44,92,25]

olddict,newdict = dict(),dict()

#using dict as mapper
for d in olddata:
	olddict[n] = d
newdata = list()
for i in range(0,len(olddata)/2):
	maxkey = max(olddict, key=olddict.get)
	maxval = olddict[maxkey]
	minkey = min(olddict, key=olddict.get)
	minval = olddict[minkey]
	if not maxkey in newdict.keys() and not minkey in newdict.keys():
		newdict[maxkey] = minval
		newdict[minkey] = maxval

for n in sorted(newdict.keys()):
#Final output
OUT = olddata,newdata

EDIT: Im also curious about this use case :smiley:

1 Like

Thank you @stillgotme, that is exactly what I need.

I am working on a script that creates attractor point form Geometry.DistanceTo, then remap the values with max value variable, so I can use it as a input for Refinery later. The problem was the fact that I needed inverse values, and since the lowest value is not in the middle of the list, List.Reverse was not the solution.

Is there anyway that your solution can be done with nodes? Just curious

hello, an alternative solution

olddata = [15, 7, 13, 4, 11, 44, 92, 25]
newdata = olddata[:]
sortlst = sorted(newdata, reverse=False)
reverslst = sorted(newdata, reverse=True)
filterlst = []
def swapfun(lst, a, b ): 
	lst[b], lst[a] = lst[a], lst[b]
	return lst

for x, y in zip(sortlst, reverslst):
	if all([z not in filterlst for z in [x,y]]):
		indexa = newdata.index(x)
		indexb = newdata.index(y)
		newdata = swapfun(newdata, indexa, indexb)
OUT = olddata, newdata