【发布时间】:2021-09-22 10:02:12
【问题描述】:
我正在玩一个简单的区块链。我想在我的代码中获取交易的总数,但是这个方法只返回一个值!这是默认值。这是我的示例链。
"chain": [
{
"index": 1,
"previous_hash": "1",
"proof": 0,
"timestamp": "2021-07-13 12:46:27.100441",
"transactions": [
{
"amount": 0,
"reciver": "-",
"sender": "-"
}
]
},
{
"index": 2,
"previous_hash": "e267a3f77fe50af86466a9bc5fce5b8285cf3eff85260f402074505c6023a085",
"proof": 115558,
"timestamp": "2021-07-13 12:48:29.790718",
"transactions": [
{
"amount": 420.69,
"reciver": "John",
"sender": "Hoomehr"
},
{
"amount": 1142,
"reciver": "John",
"sender": "yaser"
},
{
"amount": 100,
"reciver": "Miner",
"sender": "01656f68288a45f993fc8c35c3d853d1"
}
]
},
{
"index": 3,
"previous_hash": "217a9bb5994943e03cef59edac125cc33c1831dce9d3ce8424ca134068e808b5",
"proof": 48245,
"timestamp": "2021-07-13 12:49:18.885861",
"transactions": [
{
"amount": 462,
"reciver": "Yaser",
"sender": "Hoomehr"
},
{
"amount": 32,
"reciver": "John",
"sender": "Hoomehr"
},
{
"amount": 100,
"reciver": "Miner",
"sender": "01656f68288a45f993fc8c35c3d853d1"
}
]
}
]
这是我的代码:
我试图遍历每一层并做一个for循环,同时我不知道我的语法是错误还是正确。
def total_trans(self):
balance=0
for i in self.chain:
for key , value in self.chain[0].items() :
for x in self.chain[0]['transactions']:
for k , v in self.chain[0]['transactions'][0].items():
balance += sum(self.chain[0]['transactions'][0]['amount'] for i in self.chain[0]['transactions'][0])
return balance
【问题讨论】:
标签: python loops dictionary for-loop iteration