<p>我正在尝试对列表进行排序:</p>
<pre><code>[
'[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'
]
</code></pre>
<p>使用接受答案的第一部分<a href="https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside">here</a>:</p>
<p>但名单最终是这样的:</p>
<pre><code>[
' [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)'
]
</code></pre>
<p>然而,我希望<strong><em>EDW Ratio(10度)</em></strong>在排序后结束于列表的开头(索引位置0)。你知道吗</p>
<p>如何做到这一点?你知道吗</p>
<p>我的代码包括:</p>
<pre><code>#
# 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.
</code></pre>