2017-10-21 104 views
0

我希望能够遍历列表来查找列表中写入文件的元素的匹配项,并添加列表中元素的总价格。这是我到目前为止 - 只是不知道如何找到匹配的元素和添加。 - 例如您的开支名称列表可能包含多个名为“垃圾食品”的条目,并且每个条目都会有一个相应的priceList条目用于其成本。循环查找元素并根据该元素添加总价格?

def expensesManager(): 
    filePath=pickAFile() 
    file=open(filePath,"w") 
    numExpenses=requestInteger("How many weekly expenses do you currently have?") 
    expensePriceList=[None]*numExpenses 
    expenseNameList=[None]*numExpenses 
    index=0 
    total=0 
    while(index<numExpenses): 
    expenseNameList[index]=requestString("Name of Expense "+str(index+1)) 
    expensePriceList[index]=requestNumber("Price of "+ str(expenseNameList[index].capitalize())+" per week") 
    lineList=(expenseNameList[index].capitalize()+" "+str(expensePriceList[index])+"\n") 
    total=expensePriceList[index] 

    print "Your total expenditure on "+str(expenseNameList[index]).capitalize()+ " per month is $"+str((total)*4) 
    file.writelines(lineList) 

    index=index+1 


    file.close() 
+1

您能否提供一个样本,列表中您正在循环的内容? –

+0

@WillP expenseNameList是我想要循环的列表。因此,如果我在requestString函数中输入两次“bills”,它会识别出我输入了两次,并汇总了我在requestNumber函数中输入的两个不同数量的“账单”。 – sdillon87

+1

通过样本,Will P是指一些样本数据,而不是数据的名称 – thatrockbottomprogrammer

回答

0

这是将两个列表组合成默认字典的代码。然后循环并获取每个元素价格的总和。 您可以将其实施到您的个人代码中。

expenseNameList = ['bills', 'car', 'Uni', 'bills'] 
expensePriceLIst = [300, 150, 470, 150] 

    #Created defultdict 

from collections import defaultdict 
diction = defaultdict(set) 
for c, i in zip(expenseNameList, expensePriceLIst): 
    diction[c].add(i) 

for x in diction: 
    print ("Your total expenditure on",x, "per month is $"+str(sum(diction.get(x)))+".") 
+0

感谢回应,有没有办法做到这一点没有字典?我会试着看看它是如何工作的,以及我是否可以修改成for循环而不使用字典。 – sdillon87

+0

是的,我已经posed一个工作代码只使用列表。而且我编辑了我的字典代码,因为它不起作用。现在两者都应该正常工作 –

0

哇你的要求,使它只能与列表工作很奇怪,因为字典会更好。但在这里。仅使用列表的工作代码。

expenseNameList = ['bills', 'car', 'Uni', 'bills'] 
expensePriceLIst = [300, 150, 470, 150] 
TotalPrice = [] 

for x in expenseNameList: 
    b = [item for item in range(len(expenseNameList)) if expenseNameList[item] == x] 
    tempprice = 0 
    tempname = 0 
    for i in b: 
    tempprice = expensePriceLIst[i] + tempprice 
    tempname = expenseNameList[i] 
    a = ("Your total expenditure on "+tempname+ " per month is $"+str(tempprice)+".") 
    if a not in TotalPrice: 
    TotalPrice.append(a) 
for x in TotalPrice: 
    print(''.join(x)) 
+0

hi @willp上面的代码会引起以下输出:“您每月0的总支出为$ 0。” – sdillon87

+0

它适合我 –