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
結論
如果您對本教程有任何疑問,請在評論部分中提及。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP