Python: list.sort() query when list contains different element types

后端 未结 4 2123
清歌不尽
清歌不尽 2021-01-04 12:21

Greetings Pythonic world. Day 4 of learning Python 3.3 and I\'ve come across a strange property of list.sort.

I created a list of five elements: four st

4条回答
  •  感动是毒
    2021-01-04 12:44

    I am writing below answer by assuming that I know the data types in the list, might not be efficient. My idea is to partition the given list into sublists based on data type, after that sort each individual list and combine.

    input= ['b', 'a', 3, 'd', 'c']
    strs = list(filter(lambda x : type(x) ==str,input))
    ints = list(filter(lambda x: type(x) == int, input))
    
    output = sorted(strs) + sorted(ints)
    

提交回复
热议问题