Python 程式,檢查字串列表中的所有元素是否都是數字


當需要檢查字串列表中的所有元素是否都是數字時,可以使用“all”運算子。

示例

以下是同樣的演示

my_list = ["434", "823", "98", "74", '9870']

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

my_result = all(ele.isdigit() for ele in my_list)

if(my_result == True):
   print("All the elements in the list are numeric")
else:
   print("All the elements in the list are not numeric")

輸出

The list is :
['434', '823', '98', '74', '9870']
All the elements in the list are numeric

說明

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

  • 使用“all”運算子檢查每個元素是否都是數字。

  • 這是使用“isdigit”方法完成的。

  • 該運算的結果被賦給一個變數。

  • 根據結果的布林值,在控制檯上顯示相關訊息。

更新於: 2021 年 9 月 16 日

3K+ 檢視次數

開啟您職業生涯

完成課程以獲得認證

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