Python 3.x 使用字典键和TypeError进行计算
我有一本字典,格式是Python 3.x 使用字典键和TypeError进行计算,python-3.x,Python 3.x,我有一本字典,格式是 key1: [list of number] key2: [list of number] 等等 键是一个数字,其中键1
key1: [list of number]
key2: [list of number]
等等
键是一个数字,其中键1n
列表,我想计算它
x = 0
for something in dict:
if something >= max(dict.keys()) - n:
x += sum(dict[something]) // len(dict[something])
但我得到了:
TypeError: unsupported operand type(s) for -: 'str' and 'int'
and it said the error come from the 'if something >= max(dict) - n:'
请帮忙 您的类型似乎不匹配。例如,假设您有以下表达式
1 - '1'
Python有理由抱怨
TypeError: unsupported operand type(s) for -: 'int' and 'str'
因为第一个操作数是和整数,第二个操作数是字符串
还要记住
dict = {'1':[1,2,3,5,6], '2':[7,8,9,10,11]}
不一样
dict = {1:[1,2,3,5,6],2:[7,8,9,10,11]}
在第一种情况下,键的类型为字符串,在第二种情况下,键的类型为整数
使用你的代码你可以测试它
type(max(dict.keys())
将输出str
将在第二秒内输出int
因此,操作数的类型不同,它们必须都是整数才能继续计算。我认为错误来自
max(dict.keys())-n
。您应该仔细检查dict
的声明(键) 您的类型似乎不匹配。例如,假设您有以下表达式
1 - '1'
Python有理由抱怨
TypeError: unsupported operand type(s) for -: 'int' and 'str'
因为第一个操作数是和整数,第二个操作数是字符串
还要记住
dict = {'1':[1,2,3,5,6], '2':[7,8,9,10,11]}
不一样
dict = {1:[1,2,3,5,6],2:[7,8,9,10,11]}
在第一种情况下,键的类型为字符串,在第二种情况下,键的类型为整数
使用你的代码你可以测试它
type(max(dict.keys())
将输出str
将在第二秒内输出int
因此,操作数的类型不同,它们必须都是整数才能继续计算。我认为错误来自
max(dict.keys())-n
。您应该仔细检查dict
的声明(键) 你的例子需要更具体一些。看一看如何做出决定。你需要在你的例子中更具体一些。请看一下如何制作一个。