计算嵌套列表中元素的出现 [英] counting element occurrences in nested lists

查看:80
本文介绍了计算嵌套列表中元素的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常简单的问题,但是我在其他地方找不到答案,所以我会问. 查找元素出现在嵌套列表中的次数的最佳方法是什么? 例如:

This is probably quite a straightforward question, but I can't find an answer elsewhere so I'll ask. What is the best way to find the number of times an element appears in a nested list? For example:

my_list=[[a,b,c,d],[a,b,z,d],[a,c,f,e],[d,w,f,a]]

我怎么会发现"a"是列表的第一个元素多少次?或更笼统地说,"a"在my_list中出现多少次?我想有一种方法可以使用collections.Counter来做到这一点,但我一直无法弄清楚.

How would I find how many times 'a' is the first element of the list? Or more generally, how many times 'a' appears in my_list at all? I imagine there's a way to do this with collections.Counter, but I haven't been able to figure it out.

编辑 对于my_list,在计算它是否为列表的第一个元素时,我希望输出a:3.如果更改了问题以查看b是否为第二个元素,则所需的输出将为b:2

EDIT For my_list, I would like an output of a:3 when counting if it's the first element of the list. If the question was changed to see if b is the second element, the desired output would be b:2

推荐答案

使用嵌套的生成器表达式:

Use a nested generator expression:

Counter(x for sublist in my_list for x in sublist)

要计算第一个位置的项目,另一个生成器表达式将获取该项目进行计数:

To count the items in the first position, a different generator expression gets that item for counting:

Counter(sublist[0] for sublist in my_list)

演示:

>>> from collections import Counter
>>> my_list=[['a','b','c','d'],['a','b','z','d'],['a','c','f','e'],['d','w','f','a']]
>>> Counter(x for sublist in my_list for x in sublist)
Counter({'a': 4, 'd': 3, 'c': 2, 'b': 2, 'f': 2, 'e': 1, 'w': 1, 'z': 1})
>>> Counter(sublist[0] for sublist in my_list)
Counter({'a': 3, 'd': 1})

这篇关于计算嵌套列表中元素的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆