Split list of strings into column by spaces

时间:2021-12-17 21:38:00

I have a list of strings in python:

我在python中有一个字符串列表:

list =['Observed on Date 56370 at 850 F, -0.272 +/- 1.035', 
       'Observed on Date 56372 at 849 F, 0.051 +/- 0.945',
       'Observed on Date 56381 at 850 F, 0.101 +/- 0.353',]

I would like to split this into an array with columns delimited at each space in each string.

我想把它拆分成一个数组,每个字符串的每个空格都有一些列。

I'm not sure where to start with this, and any help is appreciated!

我不知道从哪里开始,任何帮助表示赞赏!

2 个解决方案

#1


1  

You're a little vague about the exact format wanted for the output, so here's a method that will produce a list of columns, each containing all the values in one of the space-delimited columns in the input:

你对输出所需的确切格式有点模糊,所以这里有一个方法可以产生一个列列表,每个列包含输入中一个空格分隔列中的所有值:

from pprint import pprint

data = ['Observed on Date 56370 at 850 F, -0.272 +/- 1.035',
        'Observed on Date 56372 at 849 F, 0.051 +/- 0.945',
        'Observed on Date 56381 at 850 F, 0.101 +/- 0.353',]

columns = list(zip(*(row.split() for row in data)))
pprint(columns)

Results:

[('Observed', 'Observed', 'Observed'),
 ('on', 'on', 'on'),
 ('Date', 'Date', 'Date'),
 ('56370', '56372', '56381'),
 ('at', 'at', 'at'),
 ('850', '849', '850'),
 ('F,', 'F,', 'F,'),
 ('-0.272', '0.051', '0.101'),
 ('+/-', '+/-', '+/-'),
 ('1.035', '0.945', '0.353')]

#2


1  

split_list = [x.split() for x in initial_list]

Also, mind naming your variable list. You're shadowing the built-in list type in Python.

另外,请注意命名变量列表。你在Python中隐藏了内置列表类型。

#1


1  

You're a little vague about the exact format wanted for the output, so here's a method that will produce a list of columns, each containing all the values in one of the space-delimited columns in the input:

你对输出所需的确切格式有点模糊,所以这里有一个方法可以产生一个列列表,每个列包含输入中一个空格分隔列中的所有值:

from pprint import pprint

data = ['Observed on Date 56370 at 850 F, -0.272 +/- 1.035',
        'Observed on Date 56372 at 849 F, 0.051 +/- 0.945',
        'Observed on Date 56381 at 850 F, 0.101 +/- 0.353',]

columns = list(zip(*(row.split() for row in data)))
pprint(columns)

Results:

[('Observed', 'Observed', 'Observed'),
 ('on', 'on', 'on'),
 ('Date', 'Date', 'Date'),
 ('56370', '56372', '56381'),
 ('at', 'at', 'at'),
 ('850', '849', '850'),
 ('F,', 'F,', 'F,'),
 ('-0.272', '0.051', '0.101'),
 ('+/-', '+/-', '+/-'),
 ('1.035', '0.945', '0.353')]

#2


1  

split_list = [x.split() for x in initial_list]

Also, mind naming your variable list. You're shadowing the built-in list type in Python.

另外,请注意命名变量列表。你在Python中隐藏了内置列表类型。