简体   繁体   English

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

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

how can i sum the integers in a list like this.我如何对这样的列表中的整数求和。

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

I have tried this way but the professor is asking to do it specifically like the list above.我已经尝试过这种方式,但教授要求按照上面的列表专门进行操作。

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])

You can use split to handle the strings:您可以使用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

Here is how you can do it.这是您如何做到的。 If I properly understood your question.如果我正确理解你的问题。

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.

相关问题 Python。 如何总结列表中的所有偶数? - Python. How to sum up all even integers in a list? Python:具有重复名称的字符串和不同整数的嵌套列表。 我怎样才能 - Python: Nested list with repeated name of strings and different integers. How can I 如何在Python中将字符串列表转换为整数? - How do I convert a list of strings to integers in Python? 如何让用户只输入 5 个整数/字符串 a 到列表中? - How can I have the user input only 5 integers/strings a into a list? 如何从字符串列表中提取整数以创建公式? - How can I extract integers from a list of strings to create a formula? 我如何在python中读取NamedTemporaryFile。 - How can i read NamedTemporaryFile in python.? 在Python中正确引用JSON。 字符串与整数和嵌套项 - Correctly referencing a JSON in Python. Strings versus Integers and Nested items Python。 使用列表中的一个步骤求和值 - Python. Sum values with a step inside list 如何通过从用户输入中删除哪个值来从(整数和字符串)列表中删除整数? - How can I delete integers from list (of integers and strings) by taking which value to delete from user input? Python。 我如何 output 每个 for 循环实例作为嵌套列表,列表内的列表 - Python. How can I output each instance of a for loop as a nested list, lists inside a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM