我有一些数据看起来像这种格式
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)
我该怎么做才能做出改变?
这个问题不清楚,可能注定会被遗忘,但如果我理解正确,这远非确定,你正在尝试做这样的事情。
array = [[2, 3, 5], [3, 4, 5], [5, 6, 7]]
#initialize the variables C1 and C2
C1 = 0
C2 = 0
#iterate the elements of the FIRST list in your list
#so 2,3,5 (I assume you have indicated 2,3,4 by mistake)
for element in array[0]:
C1+=(element-3)**2
#iterate the elements of the SECOND list in your list
#so 3,4,5
for element in array[1]:
C2+=(element-4)**2
print("C1 =", C1)
print("C2 =", C2)
输出:
C1 = 5
C2 = 2
但是你的例子是模棱两可的。也许 2,3,5 是每个子列表中的第一个元素?在这种情况下,逻辑是相同的。
#iterate the FIRST element in each sublist in your list
for element in array:
C1+=(element[0]-3)**2
如果这就是您想要做的,那么您最好这样做,使用经典循环。列表推导式(比如[x for x in array if ...]
)是高级 Python 程序员的捷径。它们做完全相同的事情,但不太清楚并且更容易出错。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句