简体   繁体   中英

splitting python 1d array into 2d array by comma

I'm relatively new to python (experience in c#), and I have a list in a text file that I dumped into a list using;

with open(fname) as f:
    content = f.readlines()
content = [x.strip() for x in content] 

The thing is, every line is in the form XXXXX, XXXXX (with varying lengths of XXXXX), and I want to convert f into a 2-dimensional array with things in the line before the comma in the first dimension and everything after in the second.

What's the best practice for doing something like that?

Just use .split(',') :

From the documentation, we can see that the string method .split will:

Return a list of the words in the string, using sep as the delimiter string.

So to give an example, taking the string :

s = "abcd, efgh"

then we can do:

s.split(', ')

to get a list :

['abcd', 'efgh']

So for your application, just throw it in the list-comprehension :

with open(fname) as f:
    content = f.readlines()
content = [x.strip().split(', ') for x in content] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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