Python 程式統計列表中元素,直到遇到元組為止?
在本文中,我們將統計列表中元素,直到遇到元組為止。
列表是 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP