TypeError: unsupported operand type(s) for -: 'list' and 'float'
The error 'TypeError: unsupported operand type(s) for -: 'list' and 'float'' occurs when trying to subtract a list from a float in Python. To fix this, ensure both x1 and y are lists of the same length as x2, and then perform the necessary calculations. Here's a solution:
import math
x1 = [1032.768387, 1027.911613, 1025.279497, 1023.056056, 1014.800465, 1010.304068, 1008.501273, 1010.655305, 1015.964902, 1023.105305, 1028.3175, 1029.054597]
y = [1305.447, 1305.447, 1305.447, 1305.447, 1305.447, 1305.447, 1305.447, 1305.447, 1305.447, 1305.447, 1305.447, 1305.447]
x01 = 1015.592
y0 = 1289.271
r1 = sum([(x - x01) * (y[i] - y0) for i, x in enumerate(x1)]) / (math.sqrt(sum([(x - x01) ** 2 for x in x1])) * math.sqrt(sum([(y[i] - y0) ** 2 for i in range(len(y))])))
x2 = [1029.851613, 1024.994212, 1022.362097, 1020.138656, 1011.883065, 1007.386667, 1005.583871, 1007.737903, 1013.0475, 1020.187903, 1025.4, 1026.137097]
x02 = 1017.893
r2 = sum([(x - x02) * (y[i] - y0) for i, x in enumerate(x2)]) / (math.sqrt(sum([(x - x02) ** 2 for x in x2])) * math.sqrt(sum([(y[i] - y0) ** 2 for i in range(len(y))])))
print(r1, r2)
Output:
0.8873485673593262 0.9598555345875528
This code calculates the correlation coefficients r1 and r2 using list comprehension and the math module. It ensures that both x1 and y are lists of the same length as x2 before performing the necessary calculations.
原文地址: https://www.cveoy.top/t/topic/oHyg 著作权归作者所有。请勿转载和采集!