📜  Python - 过滤没有空格字符串的行

📅  最后修改于: 2022-05-13 01:55:09.916000             🧑  作者: Mango

Python - 过滤没有空格字符串的行

给定 Matrix,提取字符串中没有空格的行。

例子:

方法 #1:使用列表理解+ any() + regex

在这里,我们使用正则表达式检查每个字符串中是否没有空格,any() 用于检查发现的任何带有空格的字符串,不添加该行。

Python3
# Python3 code to demonstrate working of
# Filter rows without Space Strings
# Using list comprehension + any() + regex
import re
  
# initializing list
test_list = [["gfg is", "best"], ["gfg", "good"],
             ["gfg is cool"], ["love", "gfg"]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# checking for spaces using regex
# not including row if any string has space
res = [row for row in test_list if not any(
    bool(re.search(r"\s", ele)) for ele in row)]
  
# printing result
print("Filtered Rows : " + str(res))


Python3
# Python3 code to demonstrate working of
# Filter rows without Space Strings
# Using filter() + lambda + any() + regex
import re
  
# initializing list
test_list = [["gfg is", "best"], ["gfg", "good"],
             ["gfg is cool"], ["love", "gfg"]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# checking for spaces using regex
# not including row if any string has space
res = list(filter(lambda row: not any(bool(re.search(r"\s", ele))
                                      for ele in row), test_list))
  
# printing result
print("Filtered Rows : " + str(res))


输出:

方法 #2:使用filter() + lambda + any() + regex

在此,我们使用 filter() 和 lambda函数执行过滤任务,其余所有功能都与上述方法类似。

蟒蛇3

# Python3 code to demonstrate working of
# Filter rows without Space Strings
# Using filter() + lambda + any() + regex
import re
  
# initializing list
test_list = [["gfg is", "best"], ["gfg", "good"],
             ["gfg is cool"], ["love", "gfg"]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# checking for spaces using regex
# not including row if any string has space
res = list(filter(lambda row: not any(bool(re.search(r"\s", ele))
                                      for ele in row), test_list))
  
# printing result
print("Filtered Rows : " + str(res))

输出: