繁体   English   中英

如何按字符串长度对 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_)

但如下所示,我没有得到排序结果,因为“纠缠是关键”的长度为 4,并且在“是关键资源”之后,长度为 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']

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

请帮忙! 谢谢!

试试这个:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM