假设我有一个函数,它接受某个字符串,然后我需要返回该字符串中仅出现一次的单词集。这样做的最佳方法是什么?使用 dict 有帮助吗?我尝试过一些伪代码,例如:
counter = {}
def FindWords(string):
for word in string.split()
if (word is unique): counter.append(word)
return counter
有没有更好的方法来实现这个?谢谢!
编辑:
假设我有:“这个男孩跳过了另一个男孩”。我想返回“跳跃”、“越过”和“其他”。
此外,我想将其作为一组返回,而不是列表。
最佳答案
您可以使用集合
中的计数器
并返回一组仅出现一次的单词。
from collections import Counter
sent = 'this is my sentence string this is also my test string'
def find_single_words(s):
c = Counter(s.split(' '))
return set(k for k,v in c.items() if v==1)
find_single_words(sent)
# returns:
{'also', 'sentence', 'test'}
<小时/>
要仅使用基本 Python 实用程序来执行此操作,您可以使用字典来记录出现次数,从而复制 Counter
的功能。
sent = 'this is my sentence string this is also my test string'
def find_single_words(s):
c = {}
for word in s.split(' '):
if not word in c:
c[word] = 1
else:
c[word] = c[word] + 1
return [k for k,v in c.items() if v==1]
find_single_words(sent)
# returns:
['sentence', 'also', 'test']
关于Python:返回字符串中仅出现一次的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46554248/