#!/usr/bin/pythonimport shelve #Module:Shelve is imported to achIEve persistenceAccounts = 0Victor = {'name':'Victor Hughes','Email':'victor@yahoo.com','Deposit':65000,'Accno':'SA456178','Acctype':'Savings'}Beverly = {'name':'Beverly Dsilva','Email':'bevd@hotmail.com','Deposit':23000,'Accno':'CA432178','Acctype':'Current'}def open_shelf(name='shelfile.shl'): global Accounts Accounts = shelve.open(name) #Accounts = {} Accounts['Beverly']= Beverly Accounts['Victor']= Victordef close_shelf(): Accounts.close()
我能够将值附加到货架但无法修改值.
我已经定义了一个函数Deposit(),我想从中修改shelve中存在的数据.但是它给了我以下错误:
Traceback (most recent call last): file "./functest.py",line 16,in <module> Deposit() file "/home/pavitar/Software-Development/Python/Banking/Snippets/Depositfunc.py",line 18,in Deposit for key in Accounts:TypeError: 'int' object is not iterable
这是我的功能:
#!/usr/bin/pythonimport os #This module is imported so as to use clear function in the while-loopfrom DB import * #imports the data from database DB.pydef Deposit(): while True: os.system("clear") #Clears the screen once the loop is re-invoked input = raw_input('\nEnter the A/c type: ') flag=0 for key in Accounts: if Accounts[key]['Acctype'].find(input) != -1: amt = input('\nAmount of Deposit: ') flag+=1 Accounts[key]['Deposit'] += amt if flag == 0: print "NO such Account!" if __name__ == '__main__': open_shelf() Deposit() close_shelf()
我是Python的新手.请帮忙.如果我错了,请更正我.我需要有人对这段代码的功能给出一些解释.我很困惑.
解决方法 首先,不要使用全局帐户,而是来回传递它.使用全局导致您的错误.像这样:def open_shelf(name='shelfile.shl'): Accounts = shelve.open(name) #Accounts = {} ... return Accountsdef close_shelf(Accounts): Accounts.close()def Deposit(Accounts): ... if __name__ == '__main__': Accounts = open_shelf() Deposit(Accounts) close_shelf(Accounts)
其次,不要重新定义内置函数.在Deposit()中,将raw_input的结果分配给名为input的变量:
input = raw_input('\nEnter the A/c type: ')
四行之后,您尝试使用内置输入功能:
amt = input('\nAmount of Deposit: ')
但这不起作用,因为输入已被重新定义!
第三,当迭代搁置物品时,遵循以下模式:1)抓住搁置物品,2)变异物品,3)将变异物品写回架子.像这样:
for key,acct in Accounts.iteritems(): # grab a shelved item if val['Acctype'].find(input) != -1: amt = input('\nAmount of Deposit: ') flag+=1 acct['Deposit'] += amt # mutate the item Accounts[key] = acct # write item back to shelf
(第三点建议是从hughdbrown的答案中调整过的.)
总结以上是内存溢出为你收集整理的python – 我们如何修改搁置中的数据?全部内容,希望文章能够帮你解决python – 我们如何修改搁置中的数据?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)