python 对元素是list的list对象进行统计 实现
要对元素是list的list对象进行统计,可以使用嵌套循环来遍历每个元素,并对每个元素进行统计。
下面是一个简单的示例代码:
def count_elements(lst):
count = {}
for sublist in lst:
for element in sublist:
if element in count:
count[element] += 1
else:
count[element] = 1
return count
# 测试代码
list_of_lists = [[1, 2, 3], [2, 3, 4], [1, 2, 2, 3]]
result = count_elements(list_of_lists)
print(result)
输出结果为:
{1: 2, 2: 4, 3: 3, 4: 1}
在上述代码中,count_elements
函数接受一个元素是list的list对象作为参数,并返回一个字典,其中键是元素值,值是该元素在list中出现的次数。
在循环中,通过sublist
遍历每个子列表,然后通过element
遍历子列表中的每个元素。如果元素已经存在于count
字典中,则将其计数加1,否则将其添加到count
字典中,并初始化计数为1。
最后,返回统计结果的字典。
原文地址: http://www.cveoy.top/t/topic/i5Gr 著作权归作者所有。请勿转载和采集!