[英]How to sort a list of strings by numbers in the string
我的問題分為兩部分。
首先我需要對一個列表進行排序: a = ['Zone 3', 'Zone', 'Zone 9', 'Zone 10', 'Zone 5']
按區域的編號。
結果應如下所示: result = ['Zone', 'Zone 3', 'Zone 5', 'Zone 9', 'Zone 10']
我已經用下面的代碼試過了:
import numpy as np
a = ['Zone 3', 'Zone', 'Zone 9', 'Zone 10', 'Zone 5']
b = np.empty((0,2))
for i in range(0, len(a)):
if len(a[i]) > 4:
a1 = a[i].split()
a1 = np.array([[a1[0],int(a1[1])]])
if len(a[i]) == 4:
a1 = np.array([[a[i], '']])
print(a2)
b = np.append(b, a1, axis=0)
b = b[b[:,1].argsort()]
print(b)
結果:
[['Zone' '']
['Zone' '10']
['Zone' '3']
['Zone' '5']
['Zone' '9']]
問題似乎是, argsort()不會將10識別為 10,而是將其識別為 1。
folling代碼中出現的第二個問題:
seperator = ' '
b = list()
for i in range(len(a)):
c = seperator.join(b[i])
print(c)
b = np.append(b, c)
print(b)
出現錯誤異常:出現IndexError list index out of range ,但索引應該在范圍內。
我希望你能幫助我解決這些問題。
我會利用 Python 的內置排序功能。 您可以使用key
參數自定義列表的實際排序方式。
例如:
a = ['Zone 3', 'Zone', 'Zone 9', 'Zone 10', 'Zone 5']
def zone_key(l):
try:
_, v = l.split(' ')
return int(v)
except ValueError:
return 0
print(sorted(a, key=zone_key))
對於您的第二個問題:您正在嘗試訪問列表b
( b[i]
) 中的ith
元素,但您也將 b 定義為一個空列表 ( b = list()
)。 在循環i = 0
的第一次迭代中,它將嘗試訪問列表b
中不存在的元素 0,因此會導致索引錯誤。
所以很簡單
# Will hold the processed values
my_list = list()
# For every tuple in the list
for tup in a:
# Split on space
values = tup.split()
# See if the length is less than two
if len(values) < 2:
# Add a 0 if there is nothing
my_list.append((values[0], 0))
else:
# Otherwise save as it is in a tuple
my_list.append((values[0], int(values[1])))
# Then simply
my_list.sort(key= lambda x: x[1])
這將工作順利。
根據@hurlenko 檢查natsort :
from natsort import natsorted
natsorted(a, key=lambda y: y.lower())
返回一個字符串列表:
['Zone', 'Zone 3', 'Zone 5', 'Zone 9', 'Zone 10']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.