Sort a sublist of elements in a list leaving the rest in place

前端 未结 15 2295
小蘑菇
小蘑菇 2021-02-13 14:28

Say I have a sorted list of strings as in:

[\'A\', \'B\' , \'B1\', \'B11\', \'B2\', \'B21\', \'B22\', \'C\', \'C1\', \'C11\', \'C2\']

Now I wan

15条回答
  •  梦如初夏
    2021-02-13 14:55

    Most of the answers focused on the B's while I needed a more general solution as noted. Here's one:

    def _order_by_number(items):
        regex = re.compile(u'(.*?)(\d*)$') # pass a regex in for generality
        keys = {k: regex.match(k) for k in items}
        keys = {k: (v.groups()[0], int(v.groups()[1] or 0)) 
                for k, v in keys.iteritems()}
        items.sort(key=keys.__getitem__)
    

    I am still looking for a magic key however that would leave stuff in place

提交回复
热议问题