使用 https://stackoverflow.com/a/11899925 中的以下代码,我能够找到一个词是否唯一(通过比较它是否被使用一次或多次):
helloString = ['hello', 'world', 'world']
count = {}
for word in helloString :
if word in count :
count[word] += 1
else:
count[word] = 1
但是,如果我有一个包含数百个单词的字符串,我将如何计算该字符串中唯一单词的数量?
例如,我的代码有:
uniqueWordCount = 0
helloString = ['hello', 'world', 'world', 'how', 'are', 'you', 'doing', 'today']
count = {}
for word in words :
if word in count :
count[word] += 1
else:
count[word] = 1
如何将 uniqueWordCount
设置为 6
?通常,我真的很擅长解决这些类型的算法难题,但我一直没有成功解决这个问题。我觉得它就在我的 Nose 底下。
最佳答案
解决这个问题的最好方法是使用set
集合类型。 set
是一个集合,其中所有元素都是唯一的。因此:
unique = set([ 'one', 'two', 'two'])
len(unique) # is 2
您可以从一开始就使用一个集合,边做边添加单词:
unique.add('three')
这将在添加任何重复项时将其丢弃。或者,您可以收集列表中的所有元素并将列表传递给 set()
函数,届时该函数将删除重复项。我上面提供的示例显示了这种模式:
unique = set([ 'one', 'two', 'two'])
unique.add('three')
# unique now contains {'one', 'two', 'three'}
关于python - 计算列表中唯一单词的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33726361/