简体   繁体   English

我的代码不起作用?python 3

[英]My code is not working ?python 3

n=int(input())
c={}
for i in range(n):
    name=str(input())
    c[name]=list(input().split())
print(c)
query=input()
query_scores=c[query]
print(sum(query_scores))

The sum function is not working. sum函数不起作用。 It shows:表明:

TypeError: unsupported operand type(s) for +: 'int' and 'str'类型错误:不支持 + 的操作数类型:'int' 和 'str'

From sum 's description:sum的描述:

Sums start and the items of an iterable from left to right and returns the total.从左到右对 start 和 iterable 的项求和并返回总数。 start defaults to 0. The iterable's items are normally numbers, and the start value is not allowed to be a string. start 默认为 0。iterable 的项通常是数字,并且起始值不允许是字符串。

Since the sum starts to 0 (by default), you need to cast the elements you want to sum to something that can be added to 0. strings cannot.由于总和从 0 开始(默认情况下),您需要将要求和的元素转换为可以添加到 0 的元素。字符串不能。 You need to do something like this:你需要做这样的事情:

print(sum(int(x) for x in query_scores))

or, if you want to use floating numbers,或者,如果您想使用浮点数,

print(sum(float(x) for x in query_scores))

You have to convert the list items into any numeric type.您必须将列表项转换为任何数字类型。 The split function returns the string type and you are performing the sum in the str type split 函数返回字符串类型,您正在执行 str 类型的求和

c[name]=list(input().split())

Can be changed into可以改成

c[name] = [ int(i) for i in input().split()]

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

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