python - 访问区块链对象中的数据以获取钱包余额
问题描述
在尝试执行以下代码以访问区块链中的钱包余额时,我收到了错误:
TypeError: slice indices must be integers or None or have an index method
这是我使用的代码:
class Blockchain:
def __init__(self):
self.chain = [] #stores the blockchain
self.transactions = ["Plain as vanilla"]
self.create_block(proof = 1, previous_hash="0") #helps with block creation
self.nodes = set()
def create_block(self, proof, previous_hash):
""" Used to make a block """
block = {
'index': len(self.chain) + 1,
'timestamp': str(datetime.datetime.utcnow()),
'proof': proof,
'previous_hash': previous_hash,
'data': self.transactions
}
self.transactions = []
self.chain.append(block)
return block
self.balance = 0
chain = Blockchain.chain[]
i = 0
for x in range(len(chain)):
if chain[i:"data":"reciver"] or chain[i:"data":"sender"] == publickey:
io = 0
for chain[i:"data":"reciver"] in chain[i:"data"]: #loop for iterating through the dictionary
amount = int(chain[io:"data":"amount"])
self.balance = self.balance + amount
io = io + 1
if chain[i:"data":"sender"] == publickey:
amount = int(chain[i:"data":"amount"])
self.balance = self.balance - amount
i = i + 1
if chain[-1] == 0:
self.balance = 0
return self.balance
该代码应该遍历列表中的字典中的字典以查找区块链中钱包的余额,编辑:我添加了如何在链上构建块的方法
解决方案
你能提供错误信息吗?我看到您将“链”实例化为一个空列表,然后循环遍历它。
但是假设您只显示变量存在,要访问嵌套在此列表中的第二个字典中的字典,您应该使用:
chain[i]["data"]["receiver"]
推荐阅读
- monaco-editor - 摩纳哥编辑器:自定义撤消/重做
- r - 将 .SDcols 和 .SD 与 data.table 中的两组列一起使用
- go - 是否可以在不添加接口的情况下存根/模拟函数调用?
- javascript - 创建与数组中的数字不同的随机数
- r - 创建新文件时Rstudio setwd不存在
- python - 在 componentDidMount 之后从 React Web 应用程序进行 Webscraping
- eclipse - 未解决的需求:Require-Bundle: org.apache.lucene
- php - 从 JSON 到 Android 的右单引号
- sql - 加入3张桌子;从包含最新日期的特定字符串的第三个表行中选择
- c# - 如何从动态加载到自定义可收集 AssemblyLoadContext 的 DLL 中使用具有“全局”类型的 CSharpScript