我尝试为两个列表运行下面的函数,但出现错误:
TypeError: can only concatenate list (not "int") to list
它指向该行:(下面代码中的第 5 行)
y_line = ((y_1 - y_2) * act + y_2 * x_1 - y_1 * x_2) / (x_1 - x_2)
这是我的功能:
def parkes_error_zone_detailed(act, pred, diabetes_type):
def above_line(x_1, y_1, x_2, y_2, strict=False):
if x_1 == x_2:
return False
y_line = ((y_1 - y_2) * act + y_2 * x_1 - y_1 * x_2) / (x_1 - x_2)
return pred > y_line if strict else pred >= y_line
def below_line(x_1, y_1, x_2, y_2, strict=False):
return not above_line(x_1, y_1, x_2, y_2, not strict)
def parkes_type_1(act, pred):
# Zone E
if above_line(0, 150, 35, 155) and above_line(35, 155, 50, 550):
return 7
# Zone D - left upper
if (pred > 100 and above_line(25, 100, 50, 125) and
above_line(50, 125, 80, 215) and above_line(80, 215, 125, 550)):
return 6
# Zone D - right lower
if (act > 250 and below_line(250, 40, 550, 150)):
return 5
# Zone C - left upper
if (pred > 60 and above_line(30, 60, 50, 80) and
above_line(50, 80, 70, 110) and above_line(70, 110, 260, 550)):
return 4
# Zone C - right lower
if (act > 120 and below_line(120, 30, 260, 130) and below_line(260, 130, 550, 250)):
return 3
# Zone B - left upper
if (pred > 50 and above_line(30, 50, 140, 170) and
above_line(140, 170, 280, 380) and (act < 280 or above_line(280, 380, 430, 550))):
return 2
# Zone B - right lower
if (act > 50 and below_line(50, 30, 170, 145) and
below_line(170, 145, 385, 300) and (act < 385 or below_line(385, 300, 550, 450))):
return 1
# Zone A
return 0
最佳答案
在 Python 中,您可以在 any object 上实现算术运算符,例如 +
和 *
。在本例中,*
重复列表中的元素,+
连接两个列表:
>>> [1] * 4
[1, 1, 1, 1]
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
所以这是发生错误的行:
y_line = ((y_1 - y_2) * act + y_2 * x_1 - y_1 * x_2) / (x_1 - x_2)
当act
是一个列表
时,那么这部分(y_1 - y_2) * act
将重复列表y_1 - y_2
很多次。然而,这部分 y_2 * x_1 - y_1 * x_2
计算结果为整数。所以你有 some_list + some_integer
,它不起作用,因为列表上的 +
仅当另一个操作数也是列表时才有效。
我假设您想为act
中的每个项目计算这个表达式,那么您可以这样做
y_line = [((y_1 - y_2) * elem + y_2 * x_1 - y_1 * x_2) / (x_1 - x_2) for elem in act]
或使用numpy ,其中算术运算符与数字相同,例如*
将数组中的每个元素与给定的标量相乘。
关于Python 类型错误 : can only concatenate list (not "int") to list for Parkes error grid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59226409/