簡體   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