使用 Python 对字符串中的元素进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2597119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 01:02:02 来源:igfitidea点击:
Sorting elements in string with Python
提问by prosseek
I need to sort string, and I came up with the following function.
我需要对字符串进行排序,我想出了以下函数。
def mysort(comb_): str = [] size = len(comb_) for c in comb_: str.append(c) str.sort() return ''.join(str)
Is there any way to make it compact?
有没有办法让它紧凑?
回答by Ignacio Vazquez-Abrams
return ''.join(sorted(comb_))
回答by Jason Hall
def sortstr(comb_):
return ''.join(sorted(comb_))
e:f;b :(
e:f;b :(
回答by Nick
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)
回答by Zhenyu Li
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)