我可以對簡單列表進行自然排序,也可以對復雜列表中的特定鍵進行正常排序。我需要對復雜列表中的鍵進行自然排序。鑒于此程序: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 相同?
如何在 Python3 中對復雜列表進行自然排序?
慕碼人8056858
2022-06-14 09:49:12