Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用文件内容在python中创建嵌套列表_Python_List_Parsing_Nested Lists - Fatal编程技术网

使用文件内容在python中创建嵌套列表

使用文件内容在python中创建嵌套列表,python,list,parsing,nested-lists,Python,List,Parsing,Nested Lists,我有一个这样格式的文本文件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'], ] 我该怎么做?使用str.split和列表理解: with open('f

我有一个这样格式的文本文件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'],
]

我该怎么做?

使用
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']]

使用
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']]
使用内置的

具有以下输出:

[[12, 'john', 'E', 44, 'L'], [13, 'adam', 'D', 78, 'L'], [14, 'tue', 'E', 98, 'L']]
使用内置的

具有以下输出:

[[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']]
其中,表_数据为:

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

map(func,line.split())
nicer@HennyH有些人讨厌地图,所以我更喜欢信用证/<代码>映射(func,line.split())将nicer@HennyH有些人讨厌地图,所以我更喜欢信用证/