python - 我在 python 3.9 中排序有问题
问题描述
我必须编写一个代码:
- 打开一个文件
- 阅读
- 拆分它
- 如果单词不在 NewList 我必须将它们添加到它
- 按字母顺序返回该列表,但 sort() 没有返回我这是代码的链接谢谢大家 https://github.com/giuamato50/python
def sorting():
newlist=[]
file='romeo.txt'
handle=open(file)
for line in handle:
words=line.split()
for word in words:
if word not in newlist:
newlist.append(word)
x=newlist.sort()
return x
print(sorting())
解决方案
程序按字母顺序对列表进行排序,并使用列表理解来获得简洁和快速的代码。
编辑:添加 .strip() 以删除列表中的 \n
编辑 2:添加 key=lambda l: l.lower() 以按字母顺序排序,无论大小写
def sorting():
newlist=[]
file='julia.txt'
handle=open(file)
newlist= [line.strip() for line in handle for word in line.split() if word not in newlist]
return sorted(newlist, key=lambda l: l.lower())
print(sorting())
推荐阅读
- node.js - 使用 MVC Node.js 时如何连接到 MongoDB?
- c++ - c ++:如何通过套接字将结构从客户端发送到服务器并序列化?
- python - 进度条代表垂直填充而不是水平填充
- java - 项目库的开放式遥测和自动仪器
- python - 如何在Python中的列表中反转某些元组(用户通过列表的索引输入)?
- python - 异常处理导致“未解析的引用”python
- arrays - 为什么更改数组大小后结果会发生变化?
- google-kubernetes-engine - GKE 在高负载期间忽略来自 pod 的就绪探测
- c# - 从数组中计算余额/运行总计
- angular - 角度反应形式不显示错误消息