Python——提取字串長度為偶數的行
當需要提取字串長度為偶數的行時,可使用列表解析以及“all”運算子和“%”運算子。
以下是其演示:
示例
my_list = [["python", "is", "best"], ["best", "good", "python"], ["is", "better"], ["for", "coders"]]
print("The list is :")
print(my_list)
my_result = [row for row in my_list if all(len(element ) % 2 == 0 for element in row)]
print("The resultant list is :")
print(my_result)輸出
The list is : [['python', 'is', 'best'], ['best', 'good', 'python'], ['is', 'better'], ['for', 'coders']] The resultant list is : [['python', 'is', 'best'], ['best', 'good', 'python'], ['is', 'better']]
說明
定義了一個包含字串的列表,並在控制檯中顯示。
使用列表解析對列表中的元素進行迭代。
它使用“all”運算子和求餘運算子檢查這些元素是否為偶數。
如果是偶數,則將其儲存到列表中,並賦值給變數。
該變數在控制檯中顯示為輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP