I currently have two lists, which look like:
A = [[1.1,2.0,3.3][3.8,50.9,1.0][25.2,6.2,2.2]]
B = [14.4, 0.1, 7.2]
and I would like to sort A
based upon the indices of B
, such that the resulting sorted lists would look like:
sorted_A = [[3.8,50.9,1.0][25.2,6.2,2.2][1.1,2.0,3.3]]
sorted_B = [0.1,7.2,14.4]
I have tried sorting these using the zip
method, trying:
sorted_A = [a for _, a in sorted(zip(B, A))]
but I run into the following error:
"ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
Any help is appreciated, thanks!
CodePudding user response:
You can use zip
twice. Also note the key
parameter for sorted
:
from operator import itemgetter
A = [[1.1,2.0,3.3],[3.8,50.9,1.0],[25.2,6.2,2.2]]
B = [14.4, 0.1, 7.2]
sorted_A, sorted_B = zip(*sorted(zip(A, B), key=itemgetter(1)))
print(sorted_A) # ([3.8, 50.9, 1.0], [25.2, 6.2, 2.2], [1.1, 2.0, 3.3])
print(sorted_B) # (0.1, 7.2, 14.4)
You can use key=lambda x: x[1]
instead of key=itemgetter(1)
.
CodePudding user response:
if you want to sort number inside every list this is the code
def sort(lst_in):
lst_out = []
for i in lst_in:
if type(i) == list:
lst_out.append(sorted(i, key = lambda x:float(x)))
else:
lst_out.append(sorted(lst_in, key = lambda x:float(x)))
return lst_out[0]
return lst_out
print(sort([[1.1,2.0,3.3],[3.8,50.9,1.0],[25.2,6.2,2.2]]))
print(sort([14.4, 0.1, 7.2]))
the output is
[[1.1, 2.0, 3.3], [1.0, 3.8, 50.9], [2.2, 6.2, 25.2]]
[0.1, 7.2, 14.4]