自定义排序Python列表是否始终以某些字符串开头?
我正在使用Python 2.7。我有一个字符串列表,如下所示:自定义排序Python列表是否始终以某些字符串开头?,python,Python,我正在使用Python 2.7。我有一个字符串列表,如下所示: mylist = ['is_local', 'quantity_123', 'actual_cost_456', 'actual_cost_123', 'quantity_456', 'total_items_123', 'id', 'total_items_456', 'name', 'postcode'] 列表中始终包含id、name、postcode和is_local字段,但其他字段会
mylist = ['is_local', 'quantity_123', 'actual_cost_456',
'actual_cost_123', 'quantity_456', 'total_items_123',
'id', 'total_items_456', 'name', 'postcode']
列表中始终包含id
、name
、postcode
和is_local
字段,但其他字段会有所不同
我想对列表进行排序,使其始终以上面的集合字段开始,然后按字母顺序排列其他字段
例如:
mylist.sort(custom_sort)
print mylist
['id', 'name', 'postcode', 'is_local', 'actual_cost_123',
'actual_cost_456', 'quantity_123', 'quantity_456' ...]
我的问题是如何定义自定义排序
函数。我试过这个:
def custom_sort(a, b):
if a == 'id':
return 1
elif a == 'name':
return 1
elif a == 'postcode':
return 1
elif a == 'is_dispensing':
return 1
elif a > b:
return 1
else:
return -1
但随后
mylist.sort(自定义排序)
给我一个错误:TypeError:type'NoneType'的参数不可编辑
如果mylist
中没有重复的元素,可以使用set.difference
方法获取自定义列表与mylist
之间的差异,然后排序并将其附加到自定义列表中:
>>> 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']
>>>
否则,您可以使用列表:
>>> l+sorted([i for i in mylist if not i in l])
['id', 'name', 'postcode', 'is_local', 'actual_cost_123', 'actual_cost_456', 'quantity_123', 'quantity_456', 'total_items_123', 'total_items_456']
>>>