0

I have a list of strings where each string is essentially a line of data pulled in from a .csv program. 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 a a 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. Any ideas?

2
  • please fix your formatting Commented Feb 5, 2014 at 22:12
  • 2
    Use a csv.reader so your data never gets into that format. Commented Feb 5, 2014 at 22:14

1 Answer 1

4

Apply str.split on the items of the list:

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:

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.