python-2.7 - 对单词使用“排序”函数会给出一个输出,其中字母被拆分和排序
问题描述
我是 python (2.7) 和 stackoverflow 的新手。我正在尝试学习如何使用“排序”功能。当我使用“排序”功能时,句子分成单个字母并按升序对这些字母进行排序。但这不是我想要的。我想按升序对我的单词进行排序。我正在尝试运行此代码
peace = "This is one of the most useful sentences in the whole wide world."
def pinkan (one):
return sorted (one)
print pinkan (peace)
但我得到的输出是这样的:
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'T', 'c', 'd',
'd', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'f', 'f'
, 'h', 'h', 'h', 'h', 'i', 'i', 'i', 'i', 'l', 'l', 'l', 'm', 'n', 'n', 'n',
'n', 'o', 'o', 'o', 'o', 'o', 'r', 's', 's', 's', 's', 's
', 's', 't', 't', 't', 't', 'u', 'u', 'w', 'w', 'w']
我将不胜感激任何帮助/建议。谢谢 :-)
解决方案
您应该首先使用split()
生成单词列表,然后sort()
按字母升序对该列表进行排序:
peace = "This is one of the most useful sentences in the whole wide world."
terms = peace.split()
terms.sort(key=str.lower)
output = " ".join(terms)
print(output)
['in', 'is', 'most', 'of', 'one', 'sentences', 'the', 'the', 'This', 'useful',
'whole', 'wide', 'world.']
推荐阅读
- python - 我是否需要跟踪 asyncio 事件循环,或者我可以在需要时调用 asyncio.get_event_loop 吗?
- arrays - 在 Bash 中为每个数组元素添加一个序号
- html - html中的内联样式
- mapbox-gl-js - 如何使用 addLayer() 向 Mapbox 添加标准标记
- python - 在 Python 中动态突出显示不符合阈值的行
- google-cloud-firestore - 无法使用通配符和 onDelete 触发器上传 Firestore 云功能?
- visual-studio - 如何将现有的编辑器/分类器与新的文件扩展名相关联?
- javascript - 如何在javascript中始终选择不同的变量?
- spring - 调用控制器端点时的连接问题,我们该如何处理?[Spring 和 Kotlin]
- python - 在环境中安装点图后,我仍然得到 ImportError: No module named dotmap 尝试运行笔记本时