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” 運算子,以便過濾任何字串。

  • 將此結果分配給一個變數。

  • 將此顯示為控制檯上的輸出。

更新於:14-9-2021

144 次瀏覽量

開啟您的職業生涯

完成課程認證

開始學習
廣告
© . All rights reserved.