2017-10-15 78 views
0

我試圖使CSV閱讀器功能,我似乎無法工作,我不知道如何解決它。CSV閱讀器和隨機樣本

fileobj = open("...") # open file for reading as usual 
reader = csv.reader(fileobj) 
for row in reader: 
    # process the row 
    first_column = row[0]  
    second_column = row[1] 
    third_column = row[2] 
fileobj.close() 

print(random.sample(first_column, 2)) 

據我所知,first_column只給了我該列的底部值,因此不允許我打印隨機樣本。我不知道如何解決這個問題。

任何幫助是極大的讚賞

回答

2

這可以使用一個典型的transpositioning模式zip(*...)做:

with open("...") as fileobj: # open file with context manager as recommended ;) 
    reader = csv.reader(fileobj) 
    rows = list(reader) # if you need the rows as well 
    columns = list(zip(*rows)) # you can just use the fresh reader here as well 
    # columns = zip(*rows) # suffices in Python2 
print(random.sample(columns[0], 2)) 

查看zipargument unpacking的文檔。

+0

我得到一個TypeError:'zip'在試圖不知道這是什麼意思的時候不能下載' –

+0

Yup在Python3中,zip返回一個迭代器,而不是一個列表。更新... – schwobaseggl

+0

謝謝!現在完美的工作! –