i bit confused on how classes work in python.
i wanted sort input in natural way , found solution:
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 comments) ''' return [ atoi(c) c in re.split('(\d+)', text) ] alist=[ "something1", "something12", "something17", "something2", "something25", "something29"] alist.sort(key=natural_keys)
works charm.
now wanted include solution in class.
class __test(): def atoi(self,text): return int(text) if text.isdigit() else text def natural_keys(self,text): return [ self.atoi(c) c in re.split('(\d+)', text) ] b = __test() alist=[ "something1", "something12", "something17", "something2", "something25", "something29"] alist.sort(key=b.natural_keys(alist))
which not work since alist given natural keys list
this works charm:
class __test(): def atoi(self,text): return int(text) if text.isdigit() else text def natural_keys(self,text): return [ self.atoi(c) c in re.split('(\d+)', text) ] def sorta(self,input): = input[::] a.sort(key=natural_keys) return b = __test() alist=[ "something1", "something12", "something17", "something2", "something25", "something29"] print b.sorta(alist)
i can sort of understand have sorta() def since inside class , outside not known.
but why can not call first try? how input natural_keys end list in first try not in second?
another question why can not this:
def sorta(self,input): return input.sort(key=natural_keys)
thx in advance. sorry if wording seems confusing hope mean.
Comments
Post a Comment