我在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.sort(custom_sort)
print mylist
['id', 'name', 'postcode', 'is_local', 'actual_cost_123',
'actual_cost_456', 'quantity_123', 'quantity_456' ...]
我的问题是如何定义custom_sort
功能。我试过这个:
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(custom_sort)
给了我一个错误:TypeError: argument of type 'NoneType' is not iterable
。
答案 0 :(得分:3)
如果您在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']
>>>