简体   繁体   English

将字符串列表转换为字符串数组

[英]Converting a list of strings into an array of strings

I have a list of strings where each string is essentially a line of data pulled in from a .csv program. 我有一个字符串列表,其中每个字符串本质上是从.csv程序提取的一行数据。 For example: 例如:

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'

...etc. ...等等。

I want to convert this into aa two-dimensional list such that: 我想将其转换为一个二维列表,例如:

newData[0][0] = '2014-01-31'
newData[0][0] = '2014-01-30'
newData[1][0] = '46.83'
newData[1][1] = '47.47'

...etc ...等等

That is, I want to split the strings at each , but when I tried using data.split(",") it doesn't want to do it because it's a list. 也就是说,我想在每个字符串上拆分字符串,但是当我尝试使用data.split(",")它不想这样做,因为它是一个列表。 Any ideas? 有任何想法吗?

Apply str.split on the items of the list: str.split应用于str.split中的项目:

newData = [item.split(',') for item in data] 

Demo: 演示:

>>> 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'

As others have pointed out you should use csv module to read the data from a csv file, considering that the file contains: 正如其他人指出的那样,您应该使用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

This code will give the desired output: 此代码将提供所需的输出:

import csv
with open('file.csv') as f:
    reader = csv.reader(f)
    data = list(reader)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM