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