Python 中求和列表(帶字串型別)


在本教程中,我們將編寫一個程式,用來對列表中的所有數字求和。列表可能包含字串整數格式的數字。請看示例。

輸入

random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]

輸出

4051

按照以下步驟編寫程式。

  • 初始化列表。
  • 將變數total初始化為 0。
  • 遍歷列表。
  • 如果元素是int,請透過檢查兩個條件將其新增到total中。
    • 元素將是 int -> 檢查型別。
    • 元素將是以字串格式的數字 -> 使用isdigit()方法檢查。
  • 列印 total

示例

 現場演示

# initialzing the list
random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]
# initializing the variable total
total = 0
# iterating over the list
for element in random_list:
   # checking whether its a number or not
   if isinstance(element, int) or element.isdigit():
      # adding the element to the total
      total += int(element)
# printing the total
print(total)

輸出

如果您執行上述程式碼,將獲得以下結果。

4051

結論

如果您對本教程有任何疑問,請在評論部分中提及。

更新於: 11-Jul-2020

3K+ 檢視

開啟你的職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.