首页 > 解决方案 > 我在 python 3.9 中排序有问题

问题描述

我必须编写一个代码:

  1. 打开一个文件
  2. 阅读
  3. 拆分它
  4. 如果单词不在 NewList 我必须将它们添加到它
  5. 按字母顺序返回该列表,但 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())

标签: pythonpython-3.xlistsorting

解决方案


程序按字母顺序对列表进行排序,并使用列表理解来获得简洁和快速的代码。

编辑:添加 .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())


推荐阅读