假设我有一个函数,它接受一些字符串,然后我需要返回这个字符串中的一组单词,这些单词恰好发生一次。做这件事最好的方法是什么?用dict会有帮助吗?我试过一些伪码,比如:
counter = {}
def FindWords(string):
for word in string.split()
if (word is unique): counter.append(word)
return counter是否有更好的方法来实现这一点?谢谢!
编辑:
我说:“那个男孩跳过了另一个男孩”。我想返回“跳”、“跳”和“其他”。
另外,我想把它作为一个集合返回,而不是一个列表。
发布于 2017-10-03 22:22:43
您可以使用来自Counter的collections,并返回一组只发生一次的单词。
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']发布于 2017-10-03 22:29:03
这可能就是你想要的。
>>> counts = {}
>>> sentence = "The boy jumped over the other boy"
>>> for word in sentence.lower().split():
... if word in counts:
... counts[word]+=1
... else:
... counts[word]=1
...
>>> [word for word in counts if counts[word]==1]
['other', 'jumped', 'over']
>>> set([word for word in counts if counts[word]==1])
{'other', 'jumped', 'over'}但是,正如其他人所建议的那样,使用藏书中的defaultdict更好。
发布于 2017-10-03 22:35:44
s='The boy jumped over the other boy'
def func(s):
l=[]
s=s.split(' ') #edit for case-sensitivity here
for i in range(len(s)):
if s[i] not in s[i+1:] and s[i] not in s[i-1::-1]:
l.append(s[i])
return set(l) #convert to set and return
print(func(s))这应该挺好的。
检查每个元素是否与其前面或后面的列表中的元素匹配,如果没有,则追加它。
如果不想区分大小写,那么可以在拆分s=s.lower()或s=s.upper()之前添加它。
https://stackoverflow.com/questions/46554248
复制相似问题