繁体   English   中英

Python。 如何对包含字符串和整数的列表求和?

[英]Python. How can I sum a list with strings and integers?

我如何对这样的列表中的整数求和。

studlist = ['mario;90;80', 'denis;80;70', 'fabio;60;70']

我已经尝试过这种方式,但教授要求按照上面的列表专门进行操作。

score= [90, 80, 80, 70 , 60, 70]
name=['mario', 'denis', 'fabio']
print('the total score of',name[0], 'is' , score[0]+score[1])
print('the total score of',name[1], 'is' , score[2]+score[3])
print('the total score of',name[2], 'is' ,  score[4]+score[5])

您可以使用split来处理字符串:

studlist = ['mario;90;80', 'denis;80;70', 'fabio;60;70']

for student in studlist:
    name, *scores = student.split(';')
    print(f"The total score of {name} is {sum(int(s) for s in scores)}")

# The total score of mario is 170
# The total score of denis is 150
# The total score of fabio is 130

这是您如何做到的。 如果我正确理解你的问题。

studlist = ['mario;90;80', 'denis;80;70', 'fabio;60;70']

for name_score in studlist:
    name_score_list = name_score.split(";")
    print('the total score of',name_score_list[0], 'is' , int(name_score_list[1])+int(name_score_list[2]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM