python - 对每一行中的单词进行排序
问题描述
我有一行字,例如
ΜΔΣ,ΘΟΡ,ΑΛΒ
和一个按字母顺序对单词进行排序的python脚本
items = input("Input comma separated sequence of words")
words = [word for word in items.split(",")]
print(",".join(sorted(list(set(words)))))
输出正确答案
ΑΛΒ,ΘΟΡ,ΜΔΣ
我想输入多行输入,例如
ΜΔΣ,ΘΟΡ,ΑΛΒ
ΜΔΣ,ΣΥΝ,ΑΛΒ
并得到
ΑΛΒ,ΘΟΡ,ΜΔΣ
ΑΛΒ,ΜΔΣ,ΣΥΝ
我必须对我的代码进行哪些更改?谢谢。
解决方案
编写一个函数,将其映射到行列表中。
>>> 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
构造函数。
推荐阅读
- php - 在数组中设置特定属性
- html - 章节文章中的多行文本
- python-3.x - 我不知道语法错误在哪里,它说错误在python版本的名称上
- angular - 在 Angular 材质中创建动态交叉表
- php - PHP/SQL 在一列中查找重复行,条件是另一列不同
- java - 在浮动操作按钮内导航
- c++ - 如何找出 gsoap 服务器接收请求的以太网接口?
- c# - 你可以在 ASP.NET Core 中使用 AuthorizationHandler 中的 AuthorizationService 吗?
- netbeans - 配置 NetBeans 以使用 JMockit 作为 javaagent 执行单个单元测试
- machine-learning - 机器学习中的训练/测试数据集