我一直在试着在字典里添加两个列表的编号。问题是,我需要验证所选行和列中的值是否已经存在于字典中,如果是的话,我希望将双条目列表添加到字典中已经存在的值(另一个复式列表)中。我使用的是excel电子表格+ xlrd,这样我就可以阅读它了。我对这件事很陌生。
例如,代码正在检查指定行和列中的帐户(一个数字),假设值为10,如果它不在字典中,则会将与此计数相对应的两个值相加,例如100,0作为这个键的值。这是按计划进行的。
现在,困难的部分是当帐号已经在字典中的时候。假设这是帐号10的第二个条目。它是50,20。我想要与键"10“相关联的值是150,20。
我尝试过zip方法,但它似乎返回radomn结果,有时它加起来,有时它没有。
import xlrd
book = xlrd.open_workbook("Entry.xls")
print ("The number of worksheets is", book.nsheets)
print ("Worksheet name(s):", book.sheet_names())
sh = book.sheet_by_index(0)
print (sh.name,"Number of rows", sh.nrows,"Number of cols", sh.ncols)
liste_compte = {}
for rx in range(4, 10):
if (sh.cell_value(rowx=rx, colx=4)) not in liste_compte:
liste_compte[((sh.cell_value(rowx=rx, colx=4)))] = [sh.cell_value(rowx=rx, colx=6), sh.cell_value(rowx=rx, colx=7)]
elif (sh.cell_value(rowx=rx, colx=4)) in liste_compte:
three = [x + y for x, y in zip(liste_compte[sh.cell_value(rowx=rx, colx=4)],[sh.cell_value(rowx=rx, colx=6), sh.cell_value(rowx=rx, colx=7)])]
liste_compte[(sh.cell_value(rowx=rx, colx=4))] = three
print (liste_compte)发布于 2014-03-11 21:23:16
我不打算直接解开您的代码,但只需要帮助您提供一个通用示例,它可以实现您想要的结果:
def update_balance(existing_balance, new_balance):
for column in range(len(existing_balance)):
existing_balance[column] += new_balance[column]
def update_account(accounts, account_number, new_balance):
if account_number in accounts:
update_balance(existing_balance = accounts[account_number], new_balance = new_balance)
else:
accounts[account_number] = new_balance最后你会做一些类似的事情(假设你的xls看起来像[account_number, balance 1, balance 2]
accounts = dict()
for row in xls:
update_account(accounts = accounts,
account_number = row[0],
new_balance = row[1:2])https://stackoverflow.com/questions/22336780
复制相似问题