Python 程序用于计算列表中的元素,直到元素成为元组?
programmingpythonserver side programming
在本文中,我们将计算列表中的元素,直到元素成为元组。
列表是 Python 中最通用的数据类型,可以写为方括号之间的逗号分隔值(项)列表。列表的重要之处在于列表中的项目不必是同一类型。元组是不可变 Python 对象的序列。元组是序列,就像列表一样。元组和列表之间的主要区别在于,与列表不同,元组不能更改。元组使用括号,而列表使用方括号。
假设我们有以下列表,其中还有一个元组 -
mylist = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500]
输出应为 -
List = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] List Length = 7
使用 isinstance() 计算列表中的元素,直到元素成为元组
使用 isinstance() 方法计算列表中的元素,直到元素成为元组 −
示例
def countFunc(k): c = 0 for i in k: if isinstance(i, tuple): break c = c + 1 return c # Driver Code mylist = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] print("List with Tuple = ",mylist) print("Count of elements in a list until an element is a Tuple = ",countFunc(mylist))
输出
List with Tuple = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] Count of elements in a list until an element is a Tuple = 5
使用 type() 计算列表中的元素数量,直到元素成为元组
使用 type() 方法计算列表中的元素数量,直到元素成为元组 −
示例
def countFunc(k): c = 0 for i in k: if type(i) is tuple: break c = c + 1 return c # Driver Code mylist = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] print("List with Tuple = ",mylist) print("Count of elements in a list until an element is a Tuple = ",countFunc(mylist))
输出
List with Tuple = [25, 50, 75, 100, 125, (20, 175, 100, 87), 500] Count of elements in a list until an element is a Tuple = 5