2

I want to sort a list with four numpy arrays.

import numpy as np 
import datetime

time_origin=[]

filelist=['3.csv','2.csv','1.csv','4.csv'] 

for i in np.arange(4):
    time_origin.append(np.loadtxt(
        filelist[i],delimiter=',',skiprows=1,usecols=(0,),unpack=True)) 

time_origin.sort()

However, it doesn't work.

The expected result:

for example:

a=[array[1,2,3,4],array[6,2],array[0,12,1,4,5]]

I want to sort a based on the length of each array

the expected result is:

a=[array[6,2],array[1,2,3,4],array[0,12,1,4,5]]

2 Answers 2

5

sort using len as the sort key:

 time_origin.sort(key=len)

Python sorts lists element by element, if all elements are the same the longer list will get sorted after but [1,2,3] will get sorted before [12] because 12 > 1.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, in retrospect, a more relevant answer than my one.
3

Try using the built-in sorted function as such:

arrays = [np.array([1,2,3,4]), np.array([1,2]), np.array([1,2,3,4,5])
a = sorted(arrays, key=lambda x:len(x))

The core idea here is to use the lambda function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.