Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我在Python3.9中遇到排序问题_Python_Python 3.x_List_Sorting - Fatal编程技术网

我在Python3.9中遇到排序问题

我在Python3.9中遇到排序问题,python,python-3.x,list,sorting,Python,Python 3.x,List,Sorting,我必须编写一个代码: 打开一个文件 读一下 分开 如果单词不在新列表中,我必须将它们添加到新列表中 按字母顺序返回该列表,但sort()不返回任何值 这是代码的链接谢谢大家 在循环的每次迭代中覆盖x,这是不需要的。另外,在列表上调用.sort(),对其进行适当排序并返回None,这是您分配给x的。对于该语法,请使用sorted() 有了这一点: def sorting(): newlist=[] file='romeo.txt' handle=open(file)

我必须编写一个代码:

  • 打开一个文件
  • 读一下
  • 分开
  • 如果单词不在新列表中,我必须将它们添加到新列表中
  • 按字母顺序返回该列表,但sort()不返回任何值 这是代码的链接谢谢大家

  • 在循环的每次迭代中覆盖
    x
    ,这是不需要的。另外,在列表上调用
    .sort()
    ,对其进行适当排序并返回None,这是您分配给
    x
    的。对于该语法,请使用
    sorted()

    有了这一点:

    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)
        return sorted(newlist)
    print(sorting())
    

    有更多的方法来改进代码,但这回答了您的问题。

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

    编辑:添加了要在列表中删除的.strip()

    编辑2:Added 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())
    
    

    请将问题中的代码包含在格式化的代码块中。提供到较长代码位的链接是可以的,但是问题中的相关部分可以确保即使原始代码不再在线,问题和答案仍然有用。在问题中发布代码示例,而不是作为链接。让它成为我们可以运行的完整示例。此外,还应包括运行时出现问题的任何有用信息。如果有人想向您发送pull请求,github参考可能很有用,但是stackoverflow问题应该是一站式的,而不必去外部站点。令人困惑的是,
    sort(array)
    array.sort()
    没有做同样的事情。第一个数组保持列表不变,但返回一个新数组,数组中的元素按排序顺序排列。后者对元素进行适当排序,并返回
    None
    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())