0

我有一个这种格式的文本文件 sample.txt(空格分隔)

12 john E 44 L
13 adam D 78 L
14 tue E 98 L

我想将此文件转换为嵌套列表

table_data = [
        [12, 'john', 'E', 44, 'L'],
        [13, 'adam', 'D', 78, 'L'],
        [14, 'tue', 'E', 98, 'L'],
]

我该怎么做 ?

4

3 回答 3

5

使用str.split和列表理解:

with open('filename') as f:
   table_data = [ line.split() for line in f]

如果您希望将数字转换为整数,请编写一个附加函数来处理给定行上的每个项目:

def func(x):
    try:                                                         
        return int(x)
    except ValueError:
        return x
>>> with open('abc1') as f:
...     table_data = [[ func(x) for x in line.split()] for line in f]
...     
>>> table_data
[[12, 'john', 'E', 44, 'L'],
 [13, 'adam', 'D', 78, 'L'],
 [14, 'tue', 'E', 98, 'L']]
于 2013-08-14T05:45:28.030 回答
1

使用内置csv

from csv import reader

types = [int, str, str, int, str]

with open('sample.txt', 'rb') as f:
    table_data = [[t(v) for v, t in zip(row, types)] for row in reader(f, delimiter=' ')]
print table_data

有输出:

[[12, 'john', 'E', 44, 'L'], [13, 'adam', 'D', 78, 'L'], [14, 'tue', 'E', 98, 'L']]
于 2013-08-14T21:58:01.570 回答
0
a = '''12 john E 44 L
13 adam D 78 L
14 tue E 98 L'''

table_data = [b.split(' ') for b in a.split('\n')]
print table_data

Where table_data is:

table_data = [['12', 'john', 'E', '44', 'L'],
              ['13', 'adam', 'D', '78', 'L'],
              ['14', 'tue', 'E', '98', 'L']]
于 2013-08-14T23:04:33.020 回答