首页 > 解决方案 > 对每一行中的单词进行排序

问题描述

我有一行字,例如

ΜΔΣ,ΘΟΡ,ΑΛΒ

和一个按字母顺序对单词进行排序的python脚本

items = input("Input comma separated sequence of words")
words = [word for word in items.split(",")]
print(",".join(sorted(list(set(words)))))

输出正确答案

ΑΛΒ,ΘΟΡ,ΜΔΣ

我想输入多行输入,例如

ΜΔΣ,ΘΟΡ,ΑΛΒ
ΜΔΣ,ΣΥΝ,ΑΛΒ

并得到

ΑΛΒ,ΘΟΡ,ΜΔΣ
ΑΛΒ,ΜΔΣ,ΣΥΝ

我必须对我的代码进行哪些更改?谢谢。

标签: pythonsorting

解决方案


编写一个函数,将其映射到行列表中。

>>> def sort_unique_words(words): 
...:     return ','.join(sorted(set(words.split(',')))) 
...:                                                                                                                                                                         
>>> line = 'ΜΔΣ,ΘΟΡ,ΑΛΒ'                                                                                                                                                     
>>> sort_unique_words(line)                                                                                                                                                  
'ΑΛΒ,ΘΟΡ,ΜΔΣ'
>>>                                                                                                                                                                          
>>> lines = '''ΜΔΣ,ΘΟΡ,ΑΛΒ 
...: ΜΔΣ,ΣΥΝ,ΑΛΒ'''                                                                                                                                                          
>>>                                                                                                                                                                          
>>> '\n'.join(map(sort_unique_words, lines.splitlines()))                                                                                                                    
'ΑΛΒ,ΘΟΡ,ΜΔΣ\nΑΛΒ,ΜΔΣ,ΣΥΝ'
>>> print(_)                                                                                                                                                                 
ΑΛΒ,ΘΟΡ,ΜΔΣ
ΑΛΒ,ΜΔΣ,ΣΥΝ

我的功能与您已经做过的非常相似,请注意

[word for word in items.split(",")]

是相同的

items.split(",")

如果要在结果中包含重复项,请摆脱set构造函数。


推荐阅读