Python中的列表总数(带有字符串类型)
在本教程中,我们将编写一个将列表中所有数字相加的程序。列表可以包含字符串或整数格式的数字。参见示例。
输入值
random_list = [1, '10', 'nhooo', '2020', 'nhooo@2020', 2020]
输出结果
4051
请按照以下步骤编写程序。
初始化列表。
3用0初始化变量total。
遍历列表。
如果元素为int,则通过检查两个条件将其添加到总数中。
该元素将为int->Checktype。
元素将是字符串格式的数字->使用isdigit()方法检查。
打印总计
示例
# initialzing the list
random_list = [1, '10', 'nhooo', '2020', 'nhooo@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
结论
如果您对本教程有任何疑问,请在评论部分中提及。
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿