【发布时间】:2019-11-14 16:32:31
【问题描述】:
我正在尝试对列表进行排序:
[
'[fc] EDW Ratio (10 degrees)',
' [fc] EDW Ratio (45 degrees)',
' [fc] EDW Ratio (60 degrees)',
' [fc] EDW Ratio (25 degrees)',
' [fc] EDW Ratio (20 degrees)',
' [fc] EDW Ratio (30 degrees)',
' [fc] EDW Ratio (15 degrees)',
' [fc] EDW output factor (60 degrees)',
' [fc] Quality index'
]
使用已接受答案的第一部分here:
但是列表最终是这样的:
[
' [fc] EDW Ratio (15 degrees)',
' [fc] EDW Ratio (20 degrees)',
' [fc] EDW Ratio (25 degrees)',
' [fc] EDW Ratio (30 degrees)',
' [fc] EDW Ratio (45 degrees)',
' [fc] EDW Ratio (60 degrees)',
' [fc] EDW output factor (60 degrees)',
' [fc] Quality index',
'[fc] EDW Ratio (10 degrees)'
]
而我希望 EDW 比率(10 度) 在排序后位于列表的开头(索引位置 0)。
如何做到这一点?
我的代码包括以下内容:
#
# Method to define natural sorting used to sort lists
#
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
'''
return [ atoi(c) for c in re.split(r'(\d+)', text) ]
.
.
.
tname_list = test_names.split(",") # this outputs the exact first (unsorted) list shown above
tname_list.sort(key=natural_keys) # use human sorting defined above. This outputs the second list shown above.
【问题讨论】:
-
嗨@2one,你能告诉我们你的代码吗?
-
natural_keys为您的每个输入字符串返回什么?
标签: python python-3.x list natural-sort