开发者

Sorting elements in string with Python

开发者 https://www.devze.com 2022-12-25 20:12 出处:网络
I need to sort string, and I came up with the following function. def mysort(comb_): str = [] size = len(comb_)

I need to sort string, and I came up with the following function.

def mysort(comb_): 
    str = [] 
    size = len(comb_) 
    for c in comb_: 
   开发者_Python百科     str.append(c) 
    str.sort() 
    return ''.join(str) 

Is there any way to make it compact?


return ''.join(sorted(comb_))


def sortstr(comb_):
    return ''.join(sorted(comb_))

e:f;b :(


If you want to get a string back do this:

def sort_string(string):
    return "".join(sorted(string))

But if you want a list back, do this:

def sort_string(string):
    return sorted(string)


def sort_string(s):
    def sort_string_to_a_list(s):
        return sorted(s, lambda x,y: cmp(x.lower(), y.lower()) or cmp(x,y))
    sorted_list = sort_string_to_a_list(s)
    return ''.join(sorted_list)
0

精彩评论

暂无评论...
验证码 换一张
取 消