Python-为什么“ return list.sort()”返回None,而不返回列表?

发布于 2021-02-02 23:23:14

我已经能够验证findUniqueWords结果是否为sorted list。但是,它不返回列表。为什么?

def findUniqueWords(theList):
    newList = []
    words = []

    # Read a line at a time
    for item in theList:

        # Remove any punctuation from the line
        cleaned = cleanUp(item)

        # Split the line into separate words
        words = cleaned.split()

        # Evaluate each word
        for word in words:

            # Count each unique word
            if word not in newList:
                newList.append(word)

    answer = newList.sort()
    return answer
关注者
0
被浏览
178
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    list.sort对列表进行适当排序,即不返回新列表。写吧

    newList.sort()
    return newList
    


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    问题在这里:

    answer = newList.sort()
    

    sort不返回排序列表;而是将列表排序到位。

    采用:

    answer = sorted(newList)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看