Python中不使用Counter或字典统计嵌套字符串列表元素出现次数
嵌套列表元素统计解决方案
方法1:先摊平列表再统计
把嵌套的二维列表转换成一维列表后,直接用count()方法统计每个目标元素的出现次数:
animal = [['cat', 'cat', 'dog'], ['cat', 'cat', 'dog'], ['cat', 'cat', 'dog']] item_to_find = ['cat', 'dog'] # 摊平嵌套列表 flat_animal = [item for sublist in animal for item in sublist] # 批量统计目标元素次数 result = [flat_animal.count(item) for item in item_to_find] print(result) # 输出: [6, 3]
方法2:嵌套循环直接累加统计
不用摊平列表,直接遍历每个子列表,累加目标元素在各子列表中的出现次数:
animal = [['cat', 'cat', 'dog'], ['cat', 'cat', 'dog'], ['cat', 'cat', 'dog']] item_to_find = ['cat', 'dog'] result = [] for target in item_to_find: total = 0 for sublist in animal: total += sublist.count(target) result.append(total) print(result) # 输出: [6, 3]
两种方法都避开了collections.Counter和字典,仅依靠列表count()方法与基础循环实现,均可得到预期结果。
内容的提问来源于stack exchange,提问作者kfnwtfn
相关产品推荐
相关产品推荐

