我如何對這樣的串列中的整數求和。
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])
uj5u.com熱心網友回復:
您可以使用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
uj5u.com熱心網友回復:
這是您如何做到的。如果我正確理解你的問題。
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]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/349038.html
