2016-05-18 40 views
0

創建的列表我試圖將多列csv追加到多個列表。第1列將在列表1進入第2列會在列表2等等追加到從範圍

不過,我希望能夠在列數不硬代碼,以便它可以與多個CSV文件。所以我用列計數來分配應該有多少個列表。

努力雖然追加值,這些名單的時候我來了脫膠。我已經啓動了一個應該能夠將右列分配給右列表的計數,但是看起來循環只是在第一次循環之後退出並且不會將其他列追加到列表中。

import csv 

#open csv 
f = open('attendees1.csv') 
csv_f = csv.reader(f) 

#count columns 
first_row = next(csv_f) 
num_cols = len(first_row) 

#create multiple lists (within lists) based on column count 
d = [[] for x in xrange(num_cols)] 

#initiate count 
count = 0 

#im trying to state that whilst the count is less than the amount of columns, rows should be appended to lists, which list and which column will be defined by the [count] value. 

while count < (num_cols): 
    for row in csv_f: 
     d[count].append(row[count]) 
    count += 1 
    print count 


print d 

回答

3

迭代for row in csv_f:不重置while循環的每個實例之後,因而該循環的第一次通過後立即退出。

可以在一切讀作行的列表,然後調換它來創建列的列表:

import csv 
with open('attendees1.csv', 'r') as f: 
    csv_f = csv.reader(f) 
    first_row = next(csv_f) # Throw away the first row 
    d = [row for row in csv_f] 
    d = zip(*d) 

Transpose a matrix in Python

如果你想保留重新讀取相同的方式爲OP CSV文件,你可以做到這一點,以及(但這是極其低效):

while count < (num_cols): 
    for row in csv_f: 
     d[count].append(row[count]) 
    count += 1 
    print count 
    f.seek(0) # rewind to the beginning of the file 
    next(csv_f) # throw away the first line again 

Python csv.reader: How do I return to the top of the file?

+1

這比我剛剛制定基於現有的代碼,給予好評更加美好的答案。你可以修改你的答案來使用'with'來打開文件,因爲它目前在OP代碼中保持打開狀態?整個程序可以用4行代碼完成。 – roganjosh

+0

會閱讀這個謝謝你!是否有任何理由爲什麼迭代不會在while循環的每個實例之後休息?有沒有辦法讓它退出? –

+1

@saph_top:迭代雖然CSV文件是在文件從磁盤讀取時完成的。這樣做是爲了避免必須將整個文件讀入內存。在'while'循環的每次迭代之後重置將需要將文件倒回到開始重新開始。 – PaSTE

1

轉置行列表是非常優雅的答案。還有另一種解決方案,不太優雅,但對初學者來說更透明一點。 閱讀行,每個元素添加到相應的列表,像這樣:

for row in csv_f: 
    for i in range(len(d)): 
     d[i].append(row[i])