简体   繁体   English

自定义排序的Python列表始终带有某些字符串?

[英]Custom sort Python list with certain strings always at beginning?

I am working in Python 2.7. 我正在使用Python 2.7。 I have a list of strings like 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 will always have the id , name , postcode and is_local fields in it, but the other fields will vary. 列表中始终会包含idnamepostcodeis_local字段,但其他字段会有所不同。

I would like to sort the list so that it always starts with the set fields above, and then has the 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 is how to define the custom_sort function. 我的问题是如何定义custom_sort函数。 I've tried this: 我已经试过了:

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

But then mylist.sort(custom_sort) gives me an error: TypeError: argument of type 'NoneType' is not iterable . 但是,然后mylist.sort(custom_sort)给我一个错误: TypeError: argument of type 'NoneType' is not iterable

If you have not duplicate elements within mylist you can use set.difference method to get the difference between the custom list with mylist then sort and append it to your custom list : 如果您在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']
>>> 

Else you can use a list comprehension : 另外,您可以使用列表推导:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM