Python: How to custom order a list?

后端 未结 4 1122
北荒
北荒 2020-12-10 15:10

Obs: I know lists in python are not order-fixed, but think that this one will be. And I\'m using Python 2.4

I have a list, like (for example) this one:



        
4条回答
  •  無奈伤痛
    2020-12-10 15:36

    You could use a dictionary, that would allow you to access "Book", "Article", etc. without having to care about the order. I would put the data from that list into a dict that look like this:

    mydict = { u'Article': "somedata",
               u'Report': "someotherdata", ...}
    

    If you really want to sort your list in the way you described, you can use the list.sort with a key function that represents your particular sort order (Documentation). You need the key function as you need to access only the first element and your sorting order also is not alphabetical.

提交回复
热议问题