如何在 Python 中将字符串列表拆分为多个列表

问题描述

我有以下列表:

x=['2 5 6 7','9 11 13 15','31 52 56 94']

我的最终目标是在 jupyter notebook 中将其显示为带有列和行的表格。

这是我目前所做的:

  1. 我将列表转换为列表列表,现在我的列表如下所示:

    x=[['2 5 6 7'],['9 11 13 15'],['31 52 56 94']]

  2. 问题是我被困在如何拆分每个字符串。例如我想做的:

    [['2' '5' '6' '7'],['9' '11' '13' '15'],['31' '52' '56' '94']]

以便我可以使用以下内容使用 pandas 库打印表格

import pandas as pd
df = pd.DataFrame (x,columns=['int1','int2','int3','int4'])
print (df)

最终的输出应该像这样,列名和行名

int1 int2 int3 int4
   2    5    6    7
   9   11   13   15
  31   52   56   94

请帮助我朝着正确的方向前进。

解决方法

试试:

x=['2 5 6 7','9 11 13 15','31 52 56 94']
pd.DataFrame([s.split() for s in x],columns=['int1','int2','int3','int4'])

它给出:

  int1 int2 int3 int4
0    2    5    6    7
1    9   11   13   15
2   31   52   56   94