在字符串的 python 中按字母顺序排列
Alphabetically order in python of a string
我知道有 sort() 函数,但它在这里对我不起作用。我想按字母顺序排列如下字符串:
'S NOM V NOUN VERB'
应该是:
'NOM NOUN S VERB V'
如何在 python 中实现?
编辑:
我试过:
''.join(sorted(m[i][j]))
但这返回了非常不同的输出,例如 ABEILMNNNNOOPRSUVV
,这没有意义。
您应该将字符串拆分为一个列表,然后对其进行排序,然后将其转回字符串。这是一个例子。
old_string = "hello world abc"
string_list = old_string.split(" ") # split the string by a space, you can choose something different.
new_string = " ".join(string_list.sort()) # join list by a space.
print(new_string)
尝试以下操作:
x = 'S NOM V NOUN VERB'
x = x.split() # produces ['S', 'NOM', 'V', 'NOUN', 'VERB']
x = sorted(x) # produces ['NOM', 'NOUN', 'S', 'V', 'VERB']
x = ' '.join(x) # produces 'NOM NOUN S V VERB'
如果要颠倒 V 和 VERB 的顺序,则必须使用自定义排序函数(请参阅 sorted
函数的 'key' 关键字)。
您已经有了至少一个好的答案。你不妨把它抽象成一个函数:
def sortWords(s, delim = ' '):
return delim.join(sorted(s.split(delim)))
例如,
>>> sortWords('S NOM V NOUN VERB')
'NOM NOUN S V VERB'
我知道有 sort() 函数,但它在这里对我不起作用。我想按字母顺序排列如下字符串:
'S NOM V NOUN VERB'
应该是:
'NOM NOUN S VERB V'
如何在 python 中实现?
编辑:
我试过:
''.join(sorted(m[i][j]))
但这返回了非常不同的输出,例如 ABEILMNNNNOOPRSUVV
,这没有意义。
您应该将字符串拆分为一个列表,然后对其进行排序,然后将其转回字符串。这是一个例子。
old_string = "hello world abc"
string_list = old_string.split(" ") # split the string by a space, you can choose something different.
new_string = " ".join(string_list.sort()) # join list by a space.
print(new_string)
尝试以下操作:
x = 'S NOM V NOUN VERB'
x = x.split() # produces ['S', 'NOM', 'V', 'NOUN', 'VERB']
x = sorted(x) # produces ['NOM', 'NOUN', 'S', 'V', 'VERB']
x = ' '.join(x) # produces 'NOM NOUN S V VERB'
如果要颠倒 V 和 VERB 的顺序,则必须使用自定义排序函数(请参阅 sorted
函数的 'key' 关键字)。
您已经有了至少一个好的答案。你不妨把它抽象成一个函数:
def sortWords(s, delim = ' '):
return delim.join(sorted(s.split(delim)))
例如,
>>> sortWords('S NOM V NOUN VERB')
'NOM NOUN S V VERB'