打印某句子中出现刚好 K 次的所有单词
当需要打印某个句子中刚好出现 K 次的所有单词时,我们定义一个方法,该方法使用“split”方法、“remove”方法和“count”方法。通过传入所需参数来调用该方法并显示输出。
示例
以下是相同的演示
def key_freq_words(my_string, K):
my_list = list(my_string.split(" "))
for i in my_list:
if my_list.count(i) == K:
print(i)
my_list.remove(i)
my_string = "hi there how are you, how are u"
K = 2
print("The string is :")
print(my_string)
print"The repeated words with frequency", " are :"
key_freq_words(my_string, K)输出
The string is : hi there how are you, how are u The repeated words with frequency 2 are : how are
说明
定义了一个名为“key_freq_words”的方法,该方法将字符串和键作为参数。
该字符串根据空格进行分割,并被分配给一个列表。
遍历该列表,如果元素的计数与键值相等,则将其显示在控制台上。
一旦打印出来,它就会从列表中删除。
在方法之外,定义了一个字符串并显示在控制台上。
定义了键的值。
通过传入字符串和键来调用该方法。
输出显示在控制台上。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP