2016-01-24 70 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]