Home > Back-end >  How to sort a numpy array of strings by string length
How to sort a numpy array of strings by string length

Time:03-06

I have a numpy array of strings as follows:

vals = ['is the key resource of', 'key resource of', 'entanglement is the', 'entanglement is the key resource of', 'is the key resource', 'the key resource of', 'entanglement is the key', 'entanglement is the key resource', 'the key resource']

I need to sort the array by the length of each string to get the following:

vals = ['key resource of', 'the key resource', 'entanglement is the', 'is the key resource', 'the key resource of','entanglement is the key', 'is the key resource of', 'entanglement is the key resource', 'entanglement is the key resource of']

I tried converting it to a list and then sorting it:

vals = list(vals)
vals_ = sorted(vals, key=len)
print(vals_)

But as shown below, I don't get the sorted result as "entanglement is the key" has length 4 and is after "is the key resource of" which has length 5.

['key resource of', 'the key resource', 'entanglement is the', 'is the key resource', 'the key resource of', 'is the key resource of', 'entanglement is the key', 'entanglement is the key resource', 'entanglement is the key resource of']

I tried this but it just gives the array by sorted order of the first alphabet and not the length.

Please help! Thank you!

CodePudding user response:

Try with this:

vals = list(vals)
vals_ = sorted(vals, key=lambda s: len(s.split()))

You are ordering by number of words, not by number of characters.

  • Related