Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort a numpy array of strings by string length

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading