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

前端 未结 15 2266
小蘑菇
小蘑菇 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:49

    import re
    from collections import OrderedDict
    
    a = ['A', 'B' , 'B1', 'B11', 'B2', 'B21', 'B22', 'C', 'C1', 'C11', 'C2']
    dict = OrderedDict()
    
    def get_str(item):
      _str = list(map(str, re.findall(r"[A-Za-z]", item)))
      return _str
    
    def get_digit(item):
      _digit = list(map(int, re.findall(r"\d+", item)))
      return _digit
    
    for item in a:
      _str = get_str(item)
      dict[_str[0]] = sorted([get_digit(dig) for dig in a if _str[0] in dig])
    
    nested_result = [[("{0}{1}".format(k,v[0]) if v else k) for v in dict[k]] for k in dict.keys()]
    print (nested_result)
    # >>> [['A'], ['B', 'B1', 'B2', 'B11', 'B21', 'B22'], ['C', 'C1', 'C2', 'C11']]
    
    result = []
    for k in dict.keys():
      for v in dict[k]:
        result.append("{0}{1}".format(k,v[0]) if v else k)
    print (result)
    # >>> ['A', 'B', 'B1', 'B2', 'B11', 'B21', 'B22', 'C', 'C1', 'C2', 'C11']
    

提交回复
热议问题