Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
自定义排序Python列表是否始终以某些字符串开头?_Python - Fatal编程技术网

自定义排序Python列表是否始终以某些字符串开头?

自定义排序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字段,但其他字段会

我正在使用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' ...]
我的问题是如何定义
自定义排序
函数。我试过这个:

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']
>>>