为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Python3 中对复杂列表进行自然排序?

如何在 Python3 中对复杂列表进行自然排序?

慕码人8056858 2022-06-14 09:49:12
我可以对简单列表进行自然排序,也可以对复杂列表中的特定键进行正常排序。我需要对复杂列表中的键进行自然排序。鉴于此程序:import redef atof(text):    try:        retval = float(text)    except ValueError:        retval = text    return retvaldef 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://stackoverflow.com/a/12643073/190597    '''    return [ atof(c) for c in re.split(r'[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text) ]alist=[    "something1",    "something2",    "something10.0",    "something1.25",    "something1.105"]alist.sort(key=natural_keys)print("alist:")for i in alist: print(i)from operator import itemgetterblist=[    ['a', "something1"],    ['b', "something2"],    ['c', "something10.0"],    ['d', "something1.25"],    ['e', "something1.105"]]blist.sort(key=itemgetter(1))print("\nblist:")for i in blist: print(i[1])我得到这些结果:alist:something1something1.105something1.25something2something10.0blist:something1something1.105something1.25something10.0something2如何让 blist 排序与 alist 相同?
查看完整描述

1 回答

?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

您可以使用 alambda而不是itemgetter.

blist.sort(key=lambda x: natural_keys(x[1]))


查看完整回答
反对 回复 2022-06-14
  • 1 回答
  • 0 关注
  • 107 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号