我有一个包含数字的字符串列表,但我找不到一个好的方法来对它们进行排序。
例如,我得到了类似于这样的东西:
something1
something12
something17
something2
something25
something29
使用sort()
方法。
我知道可能需要先提取数字,然后再对列表进行排序,但我不知道如何用最简单的方式做到这一点。
import re
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) ]
alist=[
"something1",
"something12",
"something17",
"something2",
"something25",
"something29"]
alist.sort(key=natural_keys)
print(alist)
['something1', 'something2', 'something12', 'something17', 'something25', 'something29']
PS. 我已经改变了我的答案,使用Toothy在评论区发布的自然排序实现这里,因为它比我的原始答案快得多。
如果您希望使用浮点数对文本进行排序,则需要将正则表达式从匹配整数的表达式(即(\d+)
)更改为可以匹配浮点数的正则表达式:
import re
def atof(text):
try:
retval = float(text)
except ValueError:
retval = text
return retval
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)
float regex comes from https://dev59.com/FGcs5IYBdhLWcg3wtmID#12643073
'''
return [ atof(c) for c in re.split(r'[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text) ]
alist=[
"something1",
"something2",
"something1.0",
"something1.25",
"something1.105"]
alist.sort(key=natural_keys)
print(alist)
['something1', 'something1.0', 'something1.105', 'something1.25', 'something2']
return [ atoi(c) for c in re.split('(\d+)', someobject.sometextproperty) ]
即可。 - Jonnyattr1 = set(...)
会将 attr1
变成一个集合。集合没有 sort
方法,所以 attr1.sort
会引发 AttributeError
。可以尝试使用 attr1 = list(set(all_names))
,因为列表确实有 sort
方法。 - unutbu
list_name.sort(key=lambda x: float(x.strip('something')))
? - altroware