Python – 使用特定字元的字串篩選元組


在需要使用特定字元的字串篩選元組時,會使用列表解析和“all”運算子。

示例

以下是對相同內容的演示:

my_list = [('pyt', 'best'), ('pyt', 'good'), ('fest', 'pyt')]

print("The list is :")
print(my_list)

char_string = 'pyestb'

my_result = [index for index in my_list if all(all(sub in char_string for sub in element) for element in index)]

print("The result is : ")
print(my_result)

輸出

The list is :
[('pyt', 'best'), ('pyt', 'good'), ('fest', 'pyt')]
The result is :
[('pyt', 'best')]

說明

  • 定義了一個元組列表並在控制檯上顯示。

  • 定義了一個字串。

  • 使用列表解析遍歷列表,“all”運算子用於元素上,以檢查列表中任何元素中是否存在該特定字串。

  • 將其轉換為列表,並將其分配給一個變數。

  • 這是在控制檯上顯示的輸出。

更新於: 08-09-2021

170 瀏覽量

開啟你的職業

完成課程認證

立即開始
廣告
© . All rights reserved.