循环遍历列表以查找元素并根据该元素添加总价格?

时间:2017-10-21 05:04:20

标签: python list loops indexing

我希望能够遍历列表以查找列表中写入文件的元素的匹配项,并添加为列表中的元素指定的总价格。这是我到目前为止 - 只是不知道如何找到元素的匹配和添加。 - 例如您的费用名称列表可能包含多个名为“垃圾食品”的条目,并且每个条目的成本都会有相应的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()

2 个答案:

答案 0 :(得分: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)))+".")

答案 1 :(得分: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))