2017-10-21 1 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 함수에 두 번 "청구서"를 입력하면이 값을 두 번 입력하고 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

예, 목록을 사용하는 경우에만 작업 코드를 pos7했습니다. 그리고 작동하지 않아서 사전 코드를 편집했습니다. 이제 모두 잘 작동해야합니다. –

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

내게 잘 작동합니다. –

관련 문제