Custom sort Python list with certain strings always at beginning? -
i working in python 2.7. have list of strings this:
mylist = ['is_local', 'quantity_123', 'actual_cost_456', 'actual_cost_123', 'quantity_456', 'total_items_123', 'id', 'total_items_456', 'name', 'postcode']
the list have id
, name
, postcode
, is_local
fields in it, other fields vary.
i sort list starts set fields above, , has other fields in alphabetical order.
for example:
mylist.sort(custom_sort) print mylist ['id', 'name', 'postcode', 'is_local', 'actual_cost_123', 'actual_cost_456', 'quantity_123', 'quantity_456' ...]
my problem how define custom_sort
function. i've tried this:
def custom_sort(a, b): if == 'id': return 1 elif == 'name': return 1 elif == 'postcode': return 1 elif == 'is_dispensing': return 1 elif > b: return 1 else: return -1
but mylist.sort(custom_sort)
gives me error: typeerror: argument of type 'nonetype' not iterable
.
if have not duplicate elements within mylist
can use set.difference
method difference between custom list mylist
sort , append custom list :
>>> l=['id', 'name', 'postcode', 'is_local'] >>> l+sorted(set(mylist).difference(l)) ['id', 'name', 'postcode', 'is_local', 'actual_cost_123', 'actual_cost_456', 'quantity_123', 'quantity_456', 'total_items_123', 'total_items_456'] >>>
else can use list comprehension :
>>> l+sorted([i in mylist if not in l]) ['id', 'name', 'postcode', 'is_local', 'actual_cost_123', 'actual_cost_456', 'quantity_123', 'quantity_456', 'total_items_123', 'total_items_456'] >>>
Comments
Post a Comment