2017-10-21 103 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

它適合我 –