报错程序
import numpy as np
b = [[2,3,4]
[2,3,4]]
c = [[1,2,3]
[1,2,3]]
B = [np.sum(np.abs(a - c)) for a in b]
print(B)
# 报错行:b = [[2,3,4]
# TypeError: list indices must be integers or slices, not tuple
# 列表索引必须是整数或片,而不是元组
列表索引必须是整数或片,而不是元组
下面是修改过程:
1 修改b和c。
修改后程序报错改变
import numpy as np
b = [[2,3,4], # 注意加逗号
[2,3,4]]
c = [[1,2,3],
[1,2,3]]
B = [np.sum(np.abs(a - c)) for a in b]
print(B)
# 报错行:B = [np.sum(np.abs(a - c)) for a in b]
# TypeError: unsupported operand type(s) for -: 'list' and 'list'
# 减号不能用于list和list之间
注意:b的以下写法会报错
b = [[2,3,4]
[2,3,4]]
b = [[2,3,4] [2,3,4]]
b = [[2,3,4];
[2,3,4]]
b = [[2,3,4]; [2,3,4]]
b的以下写法正确(要用逗号!)
b = [[2,3,4],
[2,3,4]]
b = [[2,3,4], [2,3,4]]
2 增加numpy的array,用numpy里的array转化成元组 : dataSet=np.array(dataSet)
修改后程序:
import numpy as np
b = [[2,3,4],
[2,3,4]]
c = [[1,2,3],
[1,2,3]]
# add
b = np.array(b)
c = np.array(c)
B = [np.sum(np.abs(a - c)) for a in b]
print(B)
# 输出
# [6, 6]
其他解决方法: