Python —使用整數篩選元組


需要對包含整數的元組進行篩選時,可以使用簡單的迭代以及“not”運算子和“isinstance”方法。

示例

如下演示:

my_tuple = [(14, 25, "Python"), (5, 6), (3, ), ("cool", )]

print("The tuple is :")
print(my_tuple)

my_result = []
for sub in my_tuple:
   temp = True
   for element in sub:

      if not isinstance(element, int):
         temp = False
         break
   if temp :
      my_result.append(sub)

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

輸出

The tuple is :
[(14, 25, 'Python'), (5, 6), (3,), ('cool',)]
The result is :
[(5, 6), (3,)]

說明

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

  • 建立一個空列表。

  • 對列表進行迭代,使用“isinstance”方法檢視元素是否屬於整數型別。

  • 如果是,布林值會被指定為“False”。

  • 控制元件會跳出迴圈。

  • 根據布林值,會將元素追加到空列表。

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

更新時間:2021 年 9 月 8 日

134 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始學習
廣告