Python 中计算列表中元素的数量 |
您所在的位置:网站首页 › python统计元素个数的函数 › Python 中计算列表中元素的数量 |
使用 len() 函数计算 Python 列表中的元素数
在 Python 中使用 for 循环计算列表中的元素数
列表是 Python 提供的内置数据类型。它在单个变量下存储多个元素。在 Python 编程中,列表的使用非常普遍。Python 中的列表可以嵌套。 本教程将讨论计算 Python 中 List 中元素数量的不同方法。 使用 len() 函数计算 Python 列表中的元素数Python 中的列表可以存储不同数据类型的多个元素。 Python 中内置的 len() 函数可返回列表中的元素总数,而无需考虑其包含的元素类型。 我们还可以使用 len() 函数计算 Python 提供的其他三种内置数据类型的元素数量,即元组,集合和字典。 以下代码使用 len() 函数获取列表中的元素数。 list1 = ["God", "Belief", 10, 31, "Human"] print("The total number of elements in the list: ", len(list1))输出: The total number of elements in the list: 5 在 Python 中使用 for 循环计算列表中的元素数计算元素数量的另一种基本方法是利用 for 循环。循环从将计数设置为 0 开始,一直进行到最后一个元素为止;在循环迭代中,每当遇到列表中的元素时,计数就会递增 1。 以下代码使用 for 循环获取列表中的元素数。 list2 = ["Hey", 20, 14, "Look", "An Example List"] def total_elements(list): count = 0 for element in list: count += 1 return count print("The total number of elements in the list: ", total_elements(list2))输出: The total number of elements in the list: 5 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |