本文介绍了计算字符串中最小长度的唯一字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我必须写一个函数,它需要2个变量,一个句子和一个数字。该函数应返回字符串中等于或大于数字的唯一字数。示例结果应该是:I have to write a function which takes 2 variables that is a sentence and a number. The function should return the number of unique words in the string that is equal or larger than the number. The example result should be :>>> unique_func("The sky is blue and the ocean is also blue.",3) 6All I can think about the solution isdef unique_func(sentence,number): sentence_split = sentence.lower().split() for w in sentence_split: if len(w) >= number:现在我不知道如何继续我的解决方案。任何人都可以帮我吗?Now I don't know how to continue my solution. Can anyone help me?推荐答案试试这个:Try this:from string import punctuationdef unique_func(sentence, number): cnt = 0 sentence = sentence.translate(None, punctuation).lower() for w in set(sentence.split()): if len(w) >= number: cnt += 1 return cnt或者:Or:def unique_func(sentence, number): sentence = sentence.translate(None, punctuation).lower() return len([w for w in set(sentence.split()) if len(w) >= number]) 这篇关于计算字符串中最小长度的唯一字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-12 12:57