在 Python 中查找列表中的所有元素数量

pythonserver side programmingprogramming更新于 2025/10/11 8:44:17

很多时候,我们需要对列表中存在的元素进行计数以进行某些数据处理。但可能存在嵌套列表的情况,计数可能并不简单。在本文中,我们将了解如何处理计数列表中元素数量的复杂性。

使用 For 循环

在这种方法中,我们使用两个 for 循环来遍历列表的嵌套结构。在下面的程序中,我们有嵌套列表,其中内部元素包含不同数量的元素。我们还应用 len() 函数来计算扁平列表的长度。

示例

listA = [[2,9, 6], [5, 'a'], [0], [12,'c', 9, 3]]

# 给定列表
print("给定列表: ",listA)

res = len([x for y in listA for x in y])

# 打印结果
print("Total count of elements : " ,res)

输出

运行上述代码得到以下结果 −

给定列表: [[2, 9, 6], [5, 'a'], [0], [12, 'c', 9, 3]]
Total count of elements : 10

使用 Chain

在此方法中,我们应用 chain 方法,通过转换列表来取出列表中的所有内部元素,然后将其转换为列表。最后应用 len() 函数,以便找到列表中元素的数量。

示例

from itertools import chain
listA = [[2,9, 6], [5, 'a'], [0], [12,'c', 9, 3]]

# 给定列表
print("给定列表: ",listA)

res = len(list(chain(*listA)))

# 打印结果
print("Total count of elements : " ,res)

输出

运行上述代码得到以下结果 −

给定列表: [[2, 9, 6], [5, 'a'], [0], [12, 'c', 9, 3]]
Total count of elements : 10

相关文章


有用资源