【问题标题】:how to sort and append the list of words to an empty list in python如何对单词列表进行排序并将其附加到python中的空列表
【发布时间】:2014-07-28 10:26:36
【问题描述】:

我正在尝试编写一个 python 代码,它从文本文件中读取一堆行,然后将这些行拆分为单词。然后对于每个单词,它检查单词是否已经存在于列表中,如果不存在则添加到它,最后对列表进行排序并打印最终列表。这是我目前写的。

fname = raw_input("Enter file name: ")
fh = open(fname)
new = list()
for line in fh:
    line = line.rstrip()
    word = line.split()
    for w in word:
        if w not in new:
            final = new.append(w)
            result = final.sort()
    print result

但我收到以下错误.. AttributeError: 'NoneType' object has no attribute 'sort' on line 12

不知道为什么?有什么帮助吗?

谢谢 乌彭德拉

【问题讨论】:

  • .append 不返回任何内容。
  • 你只需要new.append(...)。你不需要final = new.append(...)。然后简单排序new

标签: python list append


【解决方案1】:
fname = raw_input("Enter file name: ")
with open(fname) as fh: #  use with to automatically close the file
    final = []
    new = [x.rstrip().split() for x in fh] # strip and split into sublists of words
    for ele in new: 
        for word in ele: # for every word in each sublist
            if not word in final: # if word not already in final then add word
                final.append(word)
    final.sort()  # sort 
    print final 

【讨论】:

    【解决方案2】:

    append()sort() 都在原地,不返回任何内容。

    你可以重写

            final = new.append(w)
            result = final.sort()
    

    像这样:

            final = new + [w]
            result = sorted(final)
    

    请注意,排序可以(并且应该)移出循环:这是非常昂贵的,不需要对每个单词都进行。

    最后,我建议使用集合而不是列表。它们会自动确保唯一性,将产生更简单的代码,并且通常对于此类用例具有更高的性能。

    【讨论】:

      【解决方案3】:

      文件中所有单词的排序列表:

      fname = raw_input("Enter file name: ")
      with open(fname) as fh:
          result = sorted(set(fh.read().split()))
      

      【讨论】:

        【解决方案4】:

        错误在于 .append() 方法只是附加到您现有的列表中并且不返回任何内容。所以你应该重写你的代码:

        fname = raw_input("Enter file name: ")
        fh = open(fname)
        new = list()
        for line in fh:
            line = line.rstrip()
            word = line.split()
            for w in word:
                if w not in new:
                    new.append(w)
            new.sort() #rather than sorting it in each iteration, why not just sort it at the end?
            print new
        

        【讨论】:

        • 请重新检查。我忘记修改排序方法了。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多