给定一个包含n个单词/字符串的句子。删除所有相互相似的重复单词/字符串。 例如:
null
Input : Geeks for GeeksOutput : Geeks forInput : Python is great and Java is also greatOutput : is also Java Python and great
我们可以使用 python Counter()方法 .方法非常简单。 1) 将空格分隔的输入句子拆分为单词。 2) 所以,为了首先把所有这些字符串放在一起,我们将把每个字符串加入到给定的字符串列表中。 3) 现在使用计数器方法创建一个字典,字符串作为键,频率作为值。 4) 连接每个单词都是唯一的,形成一个字符串。
python
from collections import Counter def remov_duplicates( input ): # split input string separated by space input = input .split( " " ) # now create dictionary using counter method # which will have strings as key and their # frequencies as value UniqW = Counter( input ) # joins two adjacent elements in iterable way s = " " .join(UniqW.keys()) print (s) # Driver program if __name__ = = "__main__" : input = 'Python is great and Java is also great' remov_duplicates( input ) |
输出
and great Java Python is also
替代方法:-
python
# Program without using any external library s = "Python is great and Java is also great" l = s.split() k = [] for i in l: # If condition is used to store unique string # in another list 'k' if (s.count(i)> = 1 and (i not in k)): k.append(i) print ( ' ' .join(k)) |
输出
Python is great and Java also
方法3: 另一个较短的实现:
Python3
# Python3 program string = 'Python is great and Java is also great' print ( ' ' .join( dict .fromkeys(string.split()))) |
输出
Python is great and Java also
https://youtu.be/tTjBhgJ
-无损检测
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END