Python – 过滤没有空格字符串的行
在需要过滤没有空格字符串的行时,可以使用列表解析、正则表达式,“not” 运算符和 “any” 方法。
示例
以下是演示:
import re
my_list = [["python is", "fun"], ["python", "good"],["python is cool"],["love", "python"]]
print("The list is :")
print(my_list)
my_result = [row for row in my_list if not any(bool(re.search(r"\s", element)) for element in row)]
print("The resultant list is :")
print(my_result)输出
The list is : [[‘python is’, ‘fun’], [‘python’, ‘good’], [‘python is cool’], [‘love’, ‘python’]] The resultant list is : [[‘python’, ‘good’], [‘love’, ‘python’]]
说明
将所需软件包导入到环境中。
定义并显示一个列表列表。
使用列表解析迭代列表,并使用正则表达式中的 “search” 方法查找不包含空格的字符串。
使用 “any” 方法和 “not” 运算符,以便过滤任何字符串。
将此结果分配给一个变量。
将此显示为控制台上的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP