from collections import Counter
def get_duplicate_str(list_of_str):
"""
This function returns a list of duplicate strings appeared in given list of strings.
@param list_of_str: List of strings
@return : List of strings
"""
str_counter_dict = Counter(list_of_str)
list_of_duplicate_str = [key for key in str_counter_dict.keys() if str_counter_dict[key] > 1]
return list_of_duplicate_str
# Testing the function
print(get_duplicate_str(["boy", "boy", "girl", "hand", "foot", "foot"]))
# Output
['boy', 'foot']
sentences = ['boy boy', 'girl', 'hand foot foot']
sentences_with_duplicates = [s
for s in sentences
if len(set(s.split())) != len(s.split())]
print(sentences_with_duplicates)
参考:https://docs.python.org/3.8/library/collections.html
collections
模块的Counter
类提供了一个实用程序,用于查找作为字典的字符串列表中字符串的出现次数在下面的函数中,您将获得已复制字符串的列表
您可以将此列表转换为字典,然后再次转换为列表,以便删除所有重复项
检查句子中单词的set长度,即唯一单词的长度是否与句子中所有单词的list长度不相同:
输出:
相关问题 更多 >
编程相关推荐