【问题标题】:finding all unique words from a list using loops使用循环从列表中查找所有唯一单词
【发布时间】:2013-10-21 11:13:18
【问题描述】:

我正在尝试根据从文本文件中获取的所有单词列表创建一个唯一单词列表。我唯一的问题是用于迭代两个列表的算法。

def getUniqueWords(allWords):
    uniqueWords = []
    uniqueWords.append(allWords[0])
    for i in range(len(allWords)):
        for j in range(len(uniqueWords)):
            if allWords[i] == uniqueWords[j]:
                pass
            else:
                uniqueWords.append(allWords[i])
                print uniqueWords[j]
    print uniqueWords
    return uniqueWords

如您所见,我创建了一个空列表并开始遍历两个列表。我还附加了列表中的第一项,因为由于某种原因它不会尝试匹配我假设的单词,因为在空列表中, list[0] 不存在。如果有人能帮我弄清楚如何正确地迭代这个,我就可以生成一个很棒的单词列表。

print uniqueWords[j] 只是为了调试,所以我可以看到在处理列表的过程中会出现什么

【问题讨论】:

    标签: python list loops python-2.7 iterator


    【解决方案1】:

    也许你可以使用 collections.Counter 类? (特别是如果您还想计算每个单词在源文档中出现的次数)。

    http://docs.python.org/2/library/collections.html?highlight=counter#collections.Counter

    import collections.Counter
    def getUniqueWords(allWords):
        uniqueWords = Counter()
    
        for word in allWords:
            uniqueWords[word]+=1
        return uniqueWords.keys() 
    

    另一方面,如果你只想数单词,就用一个集合:

    def getUniqueWords(allWords):
        uniqueWords =set()
    
        for word in allWords:
            uniqueWords.add(word)
        return uniquewords #if you want to return them as a set
        OR
        return list(uniquewords) #if you want to return a list  
    

    如果你被限制在循环中,并且输入相对较大,那么循环+二分搜索比循环更好——类似这样:

    def getUniqueWords(allWords):
       uw = []
       for word in allWords:
           (lo,hi) = (0,len(uw)-1)
           m = -1
           while hi>=lo and m==-1:
               mid = lo + (hi-lo)/2
               if uw[mid]==word:
                  m = mid
               elif uw[mid]<word:
                  lo = mid+1
               else:
                  hi = mid-1
           if m==-1:
               m = lo
               uw = uw[:m]+[word]+uw[m:]
       return uw 
    

    如果您的输入大约有 100000 个单词,则使用此循环与简单循环之间的区别在于您的 PC 在执行程序时不会发出噪音:)

    【讨论】:

    • 我只能使用循环。我知道如果我使用一套它会使这变得容易 1000 倍,但是是的。
    • 我明白了。那么排序列表可能是最好的方法。
    • 你不允许使用bisect模块吗?
    【解决方案2】:

    我不是 python 专家,但我认为这应该可行:

    uniqueWords = [] 
    for i in allWords:
          if not i in uniqueWords:
              uniqueWords.append(i);
    
    return uniqueWords
    

    编辑:

    我测试过,它有效,它只返回列表中唯一的单词:

    def getUniqueWords(allWords) :
        uniqueWords = [] 
        for i in allWords:
            if not i in uniqueWords:
                uniqueWords.append(i)
        return uniqueWords
    
    print getUniqueWords(['a','b','c','a','b']);
    

    ['a', 'b', 'c']

    【讨论】:

    • 是的,谢谢!我投票赞成你的答案并接受它作为解决方案
    • 为了使这项工作适用于相对较大的输入,最好保持 uniqueWords 排序,使用二进制搜索来查找下一个要添加的单词的位置。我想这是此类作业中理想的预期,因为如果您尝试计算具有 100000 个条目的数组的唯一单词,它会大大减少运行时间:)
    • 这将如何实现我还没有学习二进制搜索,教授还没有强调效率。它主要是这里是示例输入,我需要它来执行此操作,这里是示例输出。在得知不需要递归之前,我已经递归地做了一些事情。然而,他不在乎。
    【解决方案3】:

    我不喜欢(试图)要求你选择糟糕的算法的作业问题。例如,更好的选择是使用settrie

    您可以通过 2 个小改动来修复您的程序

    def getUniqueWords(allWords):
        uniqueWords = []
        uniqueWords.append(allWords[0])
        for i in range(len(allWords)):
            for j in range(len(uniqueWords)):
                if allWords[i] == uniqueWords[j]:
                    break
            else:
                uniqueWords.append(allWords[i])
                print uniqueWords[j]
        print uniqueWords
        return uniqueWords
    

    首先你需要在看到单词已经存在时停止循环

            for j in range(len(uniqueWords)):
                if allWords[i] == uniqueWords[j]:
                    break  # break out of the loop since you found a match
    

    第二个是使用for/else构造而不是if/else

            for j in range(len(uniqueWords)):
                if allWords[i] == uniqueWords[j]:
                    break
            else:
                uniqueWords.append(allWords[i])
                print uniqueWords[j]
    

    【讨论】:

    • 最初我所做的只是 uniqueWords = set(allWords) 然后我做了 uniqueWords = list(uniqueWords) 他也从未检查过元组,这很容易将我的其他一些作业从 x 数行中删除为喜欢3 行。
    【解决方案4】:

    您可以使用 set 来获取唯一的单词:

    def getUniqueWords(allWords) :
        uniqueWords = list({i for i in allWords})
        return uniqueWords
    
    print getUniqueWords(['a','b','c','a','b']);
    

    结果: ['c', 'a', 'b']

    【讨论】:

      猜你喜欢
      • 2018-07-06
      • 1970-01-01
      • 2018-12-27
      • 2021-08-27
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多