我想多学一点处理numpy数组的知识。我想要一个嵌套的循环通过一个三维的数字数组。
结果应该是:
2017年-11-11,1859年-11-12,1359
我想要被描述为嵌套循环。我的当前循环如下所示:
class Calculates(object):
def __init__(self, x, y):
self.x = x
self.y = y
def Calculator(self):
calc = self.x*self.y
return calc
playground = [['2017-11-11', 18, 17],
['2017-11-11', 16, 19],
['2017-11-11', 16, 19],
['2017-11-11', 20, 24],
['2017-11-11', 31, 15],
['2017-11-12', 10, 4],
['2017-11-12', 12, 3],
['2017-11-12', 15, 67],
['2017-11-12', 12, 23],
['2017-11-12', 1, 2]]
for date, x, y in playground:
print(date)
calc = Calculates(x,y).Calculator()
print(calc)使用此代码,我将收到:
2017年-11-11-2017年-11-11-2017年-11-2017年-11-2017年-11- 480
我想让它成为for循环的一种方式:
for date in playground:
print(date)
for x,y in playground:
calc = Calculates(x,y).Calculator()
print(calc)以获得上述结果。
但是收到以下错误消息:
ValueError:太多的值无法解包(预期的2)
发布于 2018-02-04 22:51:40
您需要将同一日期的值相乘起来,并将它们相加;一种方法是使用以日期为键的字典聚合结果;下面是一个以零作为默认值的defaultdict示例:
from collections import defaultdict
# aggregate the result into d
d = defaultdict(int)
for date, x, y in playground:
calc = Calculates(x,y).Calculator()
d[date] += calc
# print the dictionary
for date, calc in d.items():
print(date, calc)
# 2017-11-11 1859
# 2017-11-12 1359https://stackoverflow.com/questions/48613728
复制相似问题