python sorting two lists - zip, sort, zip - unorderable types: int() < NoneType() -
i have 2 lists:
a_list = ['a', 'k', 'a'] c_list = [[none, none], [13, none], ['f', none]] i sort a_list , c_list arranged according order of a_list. after sorting have:
a_list = ['a', 'a', 'k'] c_list = [[none, none], ['f', none], [13, none]] i trying zip, sort, zip approach, gives me error message @ following stage:
a_c_zip = sorted(zip(a_list,c_list)) typeerror: unorderable types: int() < nonetype() i think happening because of ambiguity of 2 a values, wonder if there work-around? after sorting a_list works without problem
i don't want write own sorting routine since slow.
you'll need specify key on sort. provided don't care order in 2 "a" entries sorted, can tell sorted @ first element of each pair generated zip (where each pair contains 1 element a_list followed 1 element c_list).
>>> a_list = ['a', 'k', 'a'] >>> c_list = [[none, none], [13, none], ['f', none]] >>> sorted(zip(a_list, c_list), key=lambda pair: pair[0]) [('a', [none, none]), ('a', ['f', none]), ('k', [13, none])] if care how 2 "a" entries sorted (that is, want them ordered in way depends on corresponding entries in c_list), you'll need figure out how want none, integers, , strings sort against each other.
one possibility treat none '' , numbers string representations, , take advantage of fact python sorts iterables values of elements left right:
>>> sorted(zip(a_list, c_list), key=lambda pair: (pair[0], ['' if elem none else str(elem) elem in pair[1]])) [('a', [none, none]), ('a', ['f', none]), ('k', [13, none])] or along lines.
the reason typeerror sorted tries compare ('a', [none, none]) against ('a', ['f', none]). since 0th element of both tuples same, has compare 1st element. since both have iterable 1st element, compares [none, none] against ['f', none] elementwise. so, must compare 'f' against none, , you can't compare none against stuff in python 3 (though in python 2).
Comments
Post a Comment