如何获得我的确定循环每行打印一个

时间:2016-03-02 17:15:08

标签: python loops

我正在尝试处理单词列表并返回一个新列表     只包含唯一的单词。我的确定循环工作,但它只会打印所有单词,而不是每行一个。谁能帮我吗?这可能是一个简单的问题,但我对Python很新。谢谢!

uniqueWords = [ ]

for word in allWords:
    if word not in uniqueWords:
        uniqueWords.append(word)
    else:
        uniqueWords.remove(word)

return uniqueWords

4 个答案:

答案 0 :(得分:1)

您可以使用str.join

>>> all_words = ['two', 'two', 'one', 'uno']
>>> print('\n'.join(get_unique_words(all_words)))
one
uno

或普通for loop

>>> for word in get_unique_words(all_words):
...     print(word)
... 
one
uno

然而,你的方法不适用于奇数:

>>> get_unique_words(['three', 'three', 'three'])
['three']

如果您的目标是让所有单词出现一次,那么这里使用collections.Counter的方法更短:

from collections import Counter

def get_unique_words(all_words):
    return [word for word, count in Counter(all_words).items() if count == 1]

答案 1 :(得分:0)

这段代码可能有所帮助,它会逐行打印出独特的单词,这是我在你的问题中所理解的:

allWords = ['hola', 'hello', 'distance', 'hello', 'hola', 'yes']

uniqueWords = [ ]

for word in allWords:
    if word not in uniqueWords:
        uniqueWords.append(word)
    else:
        uniqueWords.remove(word)

for i in uniqueWords:
    print i

答案 2 :(得分:0)

如果单词的顺序不重要,我建议您创建一个用于存储唯一单词的集合:

uniqueWords = set(allWords)

正如您可以看到运行下面的代码,它可以更快,但它可能取决于原始的单词列表:

import timeit
setup="""
word_list = [str(x) for x in range(1000, 2000)]
allWords = []
for word in word_list:
    allWords.append(word)
    allWords.append(word)
"""
smt1 = "unique = set(allWords)"
smt2 = """
uniqueWords = [ ]

for word in allWords:
    if word not in uniqueWords:
        uniqueWords.append(word)
    else:
        uniqueWords.remove(word)
"""
print("SET:", timeit.timeit(smt1, setup, number=1000))
print("LOOP:", timeit.timeit(smt2, setup, number=1000))

输出:

SET:0.03147706200002176

LOOP:0.12346845000001849

答案 3 :(得分:0)

也许这符合你的想法:

allWords=['hola', 'hello', 'distance', 'hello', 'hola', 'yes']
uniqueWords=dict()
for word in allWords:
  if word not in uniqueWords:
    uniqueWords.update({word:1})
  else:
    uniqueWords[word]+=1
for k, v in uniqueWords.items():
  if v==1:
    print(k)

打印:

distance
yes