gpt4 book ai didi

python - 如何让我的明确循环每行打印一个

转载 作者:太空宇宙 更新时间:2023-11-03 16:52:07 24 4
gpt4 key购买 nike

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

uniqueWords = [ ]

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

return uniqueWords

最佳答案

您可以使用str.join:

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

或者普通的for循环:

>>> 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]

关于python - 如何让我的明确循环每行打印一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35753897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com