'Sorting lists of floats

I would like to sort the list s and in the same manner the list s1. The code below workers for integers (after changing 2.2 to 2 and 20.6 to 20). How to adjust the code for floats, please?

s = [2.2, 3, 1, 4, 5, 3]
s1 = [20.6, 600, 10, 40, 5000, 300]

res = []
for i in range(len(s1)):
    res0 = s1[s[i]]
    res.append(res0)
print(res)

print('Sorted s:', sorted(s))
print('Ind:', sorted(range(len(s)), key=lambda k: s[k]))
print('s1 in the same manner as s:', res)


Solution 1:[1]

There is actually an error related with a part of your code res0 = s1[s[i]] that pops up:

list indices must be integers or slices, not float.

Supposed that the index is 0: s1[s[0]] -> s[0] == 2.2 -> s1[2.2]

Your code is actually using the values of s as an index for each value of s1. Your code wouldn't be able to sort a list by the manner of another list regardless if the list contains integers only.

Instead, you should add two new arrays:

s_index_list = sorted(range(len(s)), key=lambda k: s[k])
s1_sorted = sorted(s1)

One which contains the index of each value of s (Reference to this answer https://stackoverflow.com/a/7851166/18052186), and another which sort s1.

Then, you replace this bit of your code.

res0 = s1[s[i]]

by

res0 = s1_sorted[s_index_list[i]]

That way, you can sort the list s1 in the same manner as s by actually associating a value of s1 with an index from s. The result would have been:

[40, 10, 20.6, 5000, 300, 600]
Sorted s: [1, 2.2, 3, 3, 4, 5]
Ind: [2, 0, 1, 5, 3, 4]
s1 in the same manner as s: [40, 10, 20.6, 5000, 300, 600]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1