2016-01-24 102 views
-2

你能幫我解決這個問題嗎?Python - CSV到矩陣

我真的在規劃新的和想了解如何創建一個矩陣,它看起來像這樣:

matrix = {"hello":["one","two","three"], 
      "world": ["five","six","seven"], 
      "goodbye":["one","two","three"]} 

我想導入CSV,裏面有所有的字符串(一,二,三,...)在裏面,我嘗試了拆分方法,但我沒有到達那裏... 另一個問題是類別的名稱(你好,世界,再見)

你有什麼建議?

+0

你會增加的變化得到一個很好的答案,如果你發佈[最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)。例如,添加您的csv文件的示例內容。 –

+0

首先,你所引用的數據結構不是矩陣,它是一本字典,你能展示你的csv的外觀和讀取方式嗎? –

回答

0

你看過csv模塊嗎? https://docs.python.org/2/library/csv.html

import csv 

TEST_TEXT = """\ 
hello,one,two,three 
world,four,five,six 
goodbye,one,two,three""" 

TEST_FILE = TEST_TEXT.split("\n") 
#file objects iterate over newlines anyway 
#so this is how it would be when opening a file 

#this would be the minimum needed to use the csv reader object: 
for row in csv.reader(TEST_FILE): 
    print(row) 

#or to get a list of all the rows you can use this: 
as_list = list(csv.reader(TEST_FILE)) 

#splitting off the first element and using it as the key in a dictionary 
dict_I_call_matrix = {row[0]:row[1:] for row in csv.reader(TEST_FILE)} 
print(dict_I_call_matrix) 



without_csv = [row.split(",") for row in TEST_FILE] #...row in TEST_TEXT.split("\n")] 

matrix = [row[1:] for row in without_csv] 
labels = [row[0] for row in without_csv]