如何按字符串长度对 numpy 字符串数组进行排序

How to sort a numpy array of strings by string length

我有一个 numpy 字符串数组,如下所示:

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']

我需要按每个字符串的长度对数组进行排序以获得以下结果:

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']

我尝试将其转换为列表,然后对其进行排序:

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

但如下所示,我没有得到排序结果,因为“entanglement is the key”的长度为 4,并且在“is the key resource of”的长度为 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']

我试过 this 但它只是按第一个字母表的排序顺序而不是长度给出数组。

请帮忙!谢谢!

试试这个:

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

您是按字数排序,而不是按字符数排序。