2010-03-16 58 views
4

循環我希望能夠使用Python打開.csv文件是這樣的:通過在.csv文件列在Python

5,26,42,2,1,6,6 

,然後對他們進行類似此外,一些操作。

total = 0 
with open("file.csv") as csv_file: 
     for row in csv.reader(csv_file, delimiter=','): 
      for number in range(7): 
       total += int(row[number]) 

的問題是,由於.csv文件只有一個行和列的數目不詳的,我不知道如何使這項工作沒有任何硬編碼什麼樣子,或者使用真正醜陋的代碼。

是否有任何方式在Python中使用類似for columns in file的列循環?

+0

csv文件是非常大的,還是可以將整個文件讀入內存? – unutbu 2010-03-16 18:54:13

+0

它非常小,與我在問題中提供的示例.csv文件非常相似。 – 2010-03-16 18:54:58

回答

8

你就可以說

for col in row: 
    total += int(col) 

例如:

import csv 
from StringIO import StringIO 

total = 0 
for row in csv.reader(StringIO("1,2,3,4")): 
    for col in row: 
     total += int(col) 

print total # prints 10 

你之所以能做到這一點的是,csv.reader的每一行返回一個簡單的列表,這樣你就可以遍歷就像你在Python中的任何其他列表一樣。

然而,在你的情況,因爲你知道你有一個逗號分隔的整數的單行文件,你可以讓這個更簡單:

line = open("ints.txt").read().split(",") 
total = sum(int(i) for i in line) 
+1

謝謝你,完美的工作。我感到愚蠢的沒有得到:) 但是因爲我在這裏,我想知道,不會有一個「內置的」Python函數,允許你通過一個循環執行一些操作? (所以在開始時不需要初始化一個「總」值,我不確定它將如何實現)我問,因爲Python往往會簡化很多事情。 但是,再次感謝大家的答覆。他們是驚人的 – 2010-03-16 19:10:35

+0

減少(http://docs.python.org/library/functions.html#reduce)這樣做,但皺起了眉頭。 Guido解釋道(http://artima.com/weblogs/viewpost.jsp?thread=98196):「除了涉及+或*的幾個例子之外,幾乎每次我看到帶有非平凡函數參數的reduce調用時,我需要用筆和紙來繪製實際上被輸入到該函數中的內容,然後才能理解reduce的作用,因此在我看來,reduce()的適用性幾乎侷限於關聯​​運算符,並且在所有其他情況下明確地寫出積累循環更好。「 – 2010-03-16 20:16:45

3

可以遍歷列的列表就像你遍歷行的CSV閱讀:

total = 0 
with open("file.csv") as csv_file: 
    for row in csv.reader(csv_file, delimiter=','): 
     for col in row: 
      total += int(col) 

也可以添加在每次通過各行的總和,並跳過內環:

total = 0 
with open("file.csv") as csv_file: 
    for row in csv.reader(csv_file, delimiter=','): 
     total += sum(map(int, row)) 

或者您可以使用itertools.imap而不是map來保存創建額外的列表。