对列表元素中的字符串进行计数

2024-05-23 21:32:00 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个列表,l,它以句子为元素。例如l=[男孩,女孩,手足…]。我希望能够在列表中循环,找出列表中哪些元素有重复项。我尝试了计数器功能,但没有得到想要的结果:

from _collections import Counter

print(Counter(l))

我怎样才能得到想要的结果


Tags: fromimport功能元素列表counter计数器collections
3条回答

参考:https://docs.python.org/3.8/library/collections.html

collections模块的Counter类提供了一个实用程序,用于查找作为字典的字符串列表中字符串的出现次数

在下面的函数中,您将获得已复制字符串的列表

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']

您可以将此列表转换为字典,然后再次转换为列表,以便删除所有重复项

mylist = ['boy' 'boy', 'girl', ,'hand' ,'foot' ]
mylist = list(dict.fromkeys(mylist))
print(mylist) 

enter image description here

检查句子中单词的set长度,即唯一单词的长度是否与句子中所有单词的list长度不相同:

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)

输出:

['boy boy', 'hand foot foot']

相关问题 更多 >