2017-05-12 3 views
0

여러 행으로 목록을 추가해야하는이 문제를 해결하려고합니다. 하지만 해결책을 찾지 못했습니다.Python - 여러 행의 목록 합계

코드 :

g = input("Enter the file name:") 
infile = open(g,'r') 

counter = 0 
for lu in infile: 
    lu = lu.strip() 
    lulu = lu.split(",") 
    lulu = [float(i) for i in lulu] 


coo = sum(lulu) 

print("The sum of your numbers is " + str(coo) + ".") 

전류 출력 :

Enter the file name:nums.txt 
[-2.5, 2.0] 
[8.0] 
[100.0, 3.0, 5.1, 3.7] 
[6.5] 
The sum of your numbers is 6.5. 

예상 출력 : 루프에서

Enter the file name:nums.txt 
[-2.5, 2.0] 
[8.0] 
[100.0, 3.0, 5.1, 3.7] 
[6.5] 
The sum of your numbers is 125.8. 

답변

2

당신이 각 라인 lulu을 덮어 쓰는 말에 그것은 단지 마지막 줄의 합을 인쇄되어 있기 때문에.

는 다음과 같은 시도 :

g = input("Enter the file name:") 
infile = open(g,'r').read().splitlines() #make infile a list of each line in the file 

lulu = [float(j) for i in infile for j in i.split(',')] #split each line by a comma, and append each item, (converted to a float) to the list lulu 

coo = sum(lulu) 

print("The sum of your numbers is " + str(coo) + ".") 
+0

아, 내가 볼! 도와 주셔서 감사합니다! –

2

you'r 계속해서 lulu을 최신 행으로 대체하십시오. 즉, 6.5 만 유지됩니다. 루프 밖으로 lulu 목록을 가져와, 각각의 라인을 확장 :

g = input("Enter the file name:") 
infile = open(g,'r') 

lulu = [] 

counter = 0 
for lu in infile: 
    lu = lu.strip() 
    lu.split(",") 
    lulu.extend([float(i) for i in lu]) 


coo = sum(lulu) 

print("The sum of your numbers is " + str(coo) + ".")