如何在CSV中读取CSV变量中的行到多维数组?

时间:2012-06-12 14:09:16

标签: python csv multidimensional-array python-2.7

字符串如下所示:

x = '''"High";"10";"Assigned";"2012/06/12 10:11:02"
"Low";"20";"Assigned";"2012/06/12 10:11:02"
"Medium";"30";"Assigned";"2012/06/12 10:11:02"'''

我希望它是这样的:

x = [
[High, 10, Assigned, 2012/06/12 10:11:02],
[Low, 20, Assigned, 2012/06/12 10:11:02],
[Medium, 30, Assigned, 2012/06/12 10:11:02]]

什么是解析此问题的最佳方法?

3 个答案:

答案 0 :(得分:9)

>>> import csv
>>> result = [row for row in csv.reader(x.splitlines(), delimiter=';')]
>>> import pprint
>>> pprint.pprint(result)
[['High', '10', 'Assigned', '2012/06/12 10:11:02'],
 ['Low', '20', 'Assigned', '2012/06/12 10:11:02'],
 ['Medium', '30', 'Assigned', '2012/06/12 10:11:02']]

答案 1 :(得分:0)

out = []
for line in x.splitlines():
    out.append( line.split(';') )

或者,在一行中:

out = [line.split(';') for line in x.splitlines()]

答案 2 :(得分:0)

使用list comprehension的单行代码:

[line.split(';') for line in x.replace('"','').split('\n')]

给出:

[['High', '10', 'Assigned', '2012/06/12 10:11:02'],
 ['Low', '20', 'Assigned', '2012/06/12 10:11:02'],
 ['Medium', '30', 'Assigned', '2012/06/12 10:11:02']]

并在结果中删除",只留下单引号'