我有一个字符串列表,其中每个字符串基本上是从.csv程序中提取的一行数据。 例如:
data[0] = '2014-01-31,46.83,48.55,46.80,48.03,3414400,48.03'
data[1] = '2014-01-30,47.47,48.11,47.29,48.00,2083900,48.00'
...等
我想将其转换为二维列表,以便:
newData[0][0] = '2014-01-31'
newData[0][0] = '2014-01-30'
newData[1][0] = '46.83'
newData[1][1] = '47.47'
...等
也就是说,我想在每个,
分割字符串,但是当我尝试使用data.split(",")
时,它不想这样做,因为它是一个列表。有什么想法吗?
答案 0 :(得分:4)
对列表中的项目应用str.split
:
newData = [item.split(',') for item in data]
<强>演示:强>
>>> data = ['2014-01-31,46.83,48.55,46.80,48.03,3414400,48.03', '2014-01-30,47.47,48.11,47.29,48.00,2083900,48.00']
>>> newData = [item.split(',') for item in data]
>>> newData[0][0]
'2014-01-31'
>>> newData[1][0]
'2014-01-30'
正如其他人指出的那样,你应该使用csv
模块来读取csv文件中的数据,考虑到该文件包含:
2014-01-31,46.83,48.55,46.80,48.03,3414400,48.03
2014-01-30,47.47,48.11,47.29,48.00,2083900,48.00
此代码将提供所需的输出:
import csv
with open('file.csv') as f:
reader = csv.reader(f)
data = list(reader)