Python 中列表(字符串类型)的总和
pythonserver side programmingprogramming更新于 2025/8/2 0:12:17
在本教程中,我们将编写一个程序,将列表中的所有数字相加。列表可能包含字符串或整数格式的数字。查看示例。
输入
random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020]
输出
4051
按照以下步骤编写程序。
- 初始化列表。
- 3用 0 初始化变量 total。
- 遍历列表。
- 如果元素为 int,则通过以下方式将其添加到 total 中检查两个条件。
- 元素将为 int -> 检查类型。
- 元素将是字符串格式的数字 -> 使用 isdigit() 方法检查。
- 打印总数
示例
# 初始化列表 random_list = [1, '10', 'tutorialspoint', '2020', 'tutorialspoint@2020', 2020] # 初始化变量 total total = 0 # 遍历列表 for element in random_list: # 检查它是否为数字 if isinstance(element, int) or element.isdigit(): # 将元素添加到总数中 total += int(element) # 打印总数 print(total)
输出
如果您运行上述代码,那么您将获得以下结果。
4051
结论
如果您对本教程有任何疑问,请在评论部分中提及。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

