There is a list:

lst=['hello', '3', 'apple', 'boy', '2', 'ball', 'play', '6'] 

I can sort but without saving the position of the elements. Tell me how to sort this list to get this result:

 lst1=['apple', '2', 'ball', 'boy', '3', 'hello', 'play', '6'] 
  • one
    And what is the logic of inserting numbers? It seems to me easier to break into 2 lists, and then walk along two and merge them into one. - Komdosh
  • four
    What does it mean to sort while preserving the position of the elements? - TEA
  • @TEA it means that there is a non-sorted list in which there are both strings (S) and numbers (D): [S, D, S, S, D, S, S, D]. After sorting it is necessary that the order of the string and the numbers in the list remain the same [S, D, S, S, D, S, S, D] - MARKSIST
  • one
    I still do not understand. Why in the sorted list of hello after play ? - andreymal
  • @andreymal sorry for the bug fixed - MARKSIST

1 answer 1

Try:

 lst = ['hello', '3', 'apple', 'boy', '2', 'ball', 'play', '6'] lst_pos = [item.isalpha() for item in lst] print(lst_pos) # [True, False, True, True, False, True, True, False] lst_str = sorted(item for item in lst if item.isalpha()) print(lst_str) # ['apple', 'ball', 'boy', 'hello', 'play'] lst_num = sorted(item for item in lst if not item.isalpha()) print(lst_num) # ['2', '3', '6'] new_lst = [] for value in lst_pos: if value: new_lst.append(lst_str.pop(0)) else: new_lst.append(lst_num.pop(0)) print(new_lst) # ['apple', '2', 'ball', 'boy', '3', 'hello', 'play', '6']