【发布时间】:2017-02-25 16:34:11
【问题描述】:
我有一些数据看起来像这种格式
2,3,4
3,4,5
5,6,7
我将数组打包为:
with open('house_price_data.txt') as data:
substrings = data.read().split()
array = [map(int, substring.split(',')) for substring in substrings]
我的任务是对集合中的每个数据进行这样的计算:
(2-3)**2 + (3-3)**2 + (5-3)**2
(3-4)**2 + (4-4)**2 + (5-4)**2
我的预期答案是 C1 = 5 和 C2 = 2
我写了这样的代码
for [a for a, b, c in array] in range (0,2):
C1 = (([a for a, b, c in array]) - 3)**2
C2 = (([b for a, b, c in array]) - 4)**2
但它不起作用。出于for循环的目的,我认为它将读取数据2、3、5一一减去3,并将结果一一平方并将总结果相加。那么如何改进呢?
除此之外,我的代码也有问题
[a for a, b, c in array]
[b for a, b, c in array]
[c for a, b, c in array]
我需要在程序中用数组的a、b和c项的代码多次调用数组,当我在程序中有这样的代码时错误消息来了
not enough values to unpack (expected 3, got 0)
如何进行更改?
【问题讨论】:
-
公式的逻辑是什么?给定样本输入的输出是什么?
-
不清楚这些减法是从哪里来的,或者您希望如何从列表中减去一个数字...
-
@cricket_007,For循环是为C1调用数据2,3,5,为C2调用数据2,4,5。我的预期答案是 C1 = 5 和 C2 = 2
-
看起来这是您第一次尝试编写任何 Python 代码,因为您的循环根本没有任何意义,因为这种列表理解和从列表中减去整数。说真的,在这里提问之前请尝试学习一些Python。