我有一個 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']
我試過這個,但它只是按第一個字母的排序順序而不是長度給出陣列。
請幫忙!謝謝!
uj5u.com熱心網友回復:
試試這個:
vals = list(vals)
vals_ = sorted(vals, key=lambda s: len(s.split()))
您是按字數排序,而不是按字符數排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441073.html
標籤:Python 细绳 排序 numpy-ndarray
上一篇:遍歷陣列并洗掉最小的數字
