使用/sf/answers/832994781/中的以下代码,我能够找到一个单词是否唯一(通过比较它是使用过一次还是多于一次):
helloString = ['hello', 'world', 'world']
count = {}
for word in helloString :
if word in count :
count[word] += 1
else:
count[word] = 1
Run Code Online (Sandbox Code Playgroud)
但是,如果我有一个包含数百个单词的字符串,我怎么能计算该字符串中唯一单词的数量?
例如,我的代码有:
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
Run Code Online (Sandbox Code Playgroud)
我怎么可以设置uniqueWordCount到6?通常,我非常擅长解决这些类型的算法难题,但我一直没有成功解决这个问题.我觉得好像它在我的鼻子下面.
Mat*_*gor 16
解决此问题的最佳方法是使用set集合类型.A set是所有元素都是唯一的集合.因此:
unique = set([ 'one', 'two', 'two'])
len(unique) # is 2
Run Code Online (Sandbox Code Playgroud)
您可以从一开始就使用一个集合,随时添加单词:
unique.add('three')
Run Code Online (Sandbox Code Playgroud)
这将在添加时丢弃任何重复项.或者,您可以收集列表中的所有元素并将列表传递给该set()函数,该函数将删除当时的重复项.我上面提供的示例显示了这种模式:
unique = set([ 'one', 'two', 'two'])
unique.add('three')
# unique now contains {'one', 'two', 'three'}
Run Code Online (Sandbox Code Playgroud)
你有很多选择,我推荐一套,但你也可以使用一个计数器,它计算一个数字显示的数量,或者你可以查看你所做的字典的键数.
您还可以将列表转换为集合,其中所有元素都必须是唯一的.不丢弃唯一元素:
helloString = ['hello', 'world', 'world', 'how', 'are', 'you', 'doing', 'today']
helloSet = set(helloString) #=> ['doing', 'how', 'are', 'world', 'you', 'hello', 'today']
uniqueWordCount = len(set(helloString)) #=> 7
Run Code Online (Sandbox Code Playgroud)
这是进一步阅读集合的链接
您还可以使用计数器,如果您仍需要该信息,也可以告诉您单词的使用频率.
from collections import Counter
helloString = ['hello', 'world', 'world', 'how', 'are', 'you', 'doing', 'today']
counter = Counter(helloString)
len(counter) #=> 7
counter["world"] #=> 2
Run Code Online (Sandbox Code Playgroud)
在结束了你的循环,你可以检查len的count,另外,输入错误helloString的words:
uniqueWordCount = 0
helloString = ['hello', 'world', 'world', 'how', 'are', 'you', 'doing', 'today']
count = {}
for word in helloString:
if word in count :
count[word] += 1
else:
count[word] = 1
len(count) #=> 7
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16786 次 |
| 最近记录: |