移除 Python 元組中的字串


當需要從元組中刪除字串時,可以使用列表解析和“type”方法。

列表可用於儲存異構值(即任何資料型別的資料,如整數、浮點數、字串等)。

元組列表基本上包含一個列表中都用元組括起來的元組。

列表解析是遍歷列表並對其執行操作的速記。

“type”方法返回作為引數傳遞給它的可迭代類的類。

以下是相同的展示:

示例

線上演示

my_list = [('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]

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

my_result = [tuple([j for j in i if type(j) != str])
   for i in my_list]
print("The list of tuple after removing the string is : ")
print(my_result)

輸出

The list is :
[('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]
The list of tuple after removing the string is :
[(45, 67), (45, 32), (59, 13)]

解釋

  • 已定義一個元組列表,並將其顯示在控制檯上。
  • 使用列表解析對其進行迭代。
  • 將其檢查為非字串。
  • 然後將其轉換為元組,再轉換為列表。
  • 此操作的資料儲存在變數中。
  • 此變數是顯示在控制檯上的輸出。

更新日期: 2021 年 3 月 13 日

584 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.