2017-10-15 3 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

Python3では、zipはリストではなくイテレータを返します。更新されました... – schwobaseggl

+0

ありがとうございました!今すぐ完璧に動作します! –

関連する問題