Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.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_Python 2.7_Import - Fatal编程技术网

将值从文件添加到列表时使用python。仅添加该列表中的第一列

将值从文件添加到列表时使用python。仅添加该列表中的第一列,python,list,python-2.7,import,Python,List,Python 2.7,Import,我试图将两个不同文件中的值添加到两个不同的列表中。第一个文件testing.predict每行只有一个值,因此创建并打印列表 另一个文件testing每行有14个值。但是,我只想将每行的第一个值添加到列表中。测试中的每一行的布局如下:-1 2 5 2 77 4 3 76 2 9 0 2 3 8 with open('testing.predict', 'r') as x: predictList = [line.strip() for line in x] print predic

我试图将两个不同文件中的值添加到两个不同的列表中。第一个文件
testing.predict
每行只有一个值,因此创建并打印列表

另一个文件
testing
每行有14个值。但是,我只想将每行的第一个值添加到列表中。
测试中的每一行的布局如下:
-1 2 5 2 77 4 3 76 2 9 0 2 3 8

with open('testing.predict', 'r') as x:
      predictList = [line.strip() for line in x]

print predictList

with open('testing', 'r') as y:
      originalList = [line.strip() for line in y]

print originalList
当我打印出原始列表时,它会生成:

['1 1:1 2:5 3:0 4:1 5:3 6:2 7:1 8:18 9:30 10:50 11:13 12:12 13:24', 
'-1 1:0 2:1 3:0 4:0 5:1 6:1 7:1 8:10 9:10 10:12 11:10 12:6 13:16', 
'1 1:0 2:7 3:0 4:0 5:4 6:4 7:1 8:21 9:30 10:46 11:19 12:11 13:25', 
'-1 1:0 2:1 3:0 4:0 5:1 6:1 7:1 8:2 9:4 10:3 11:4 12:2 13:5', 
'-1 1:0 2:1 3:0 4:0 5:1 6:1 7:1 8:4 9:4 10:7 11:3 12:6 13:6', 
'-1 1:0 2:1 3:0 4:0 5:1 6:1 7:1 8:3 9:3 10:3 11:3 12:3 13:4', 
'-1 1:2 2:1 3:0 4:0 5:1 6:1 7:1 8:8 9:7 10:12 11:5 12:5 13:12',... ]
我只想把它打印出来:

['1','-1','1','-1','-1,'-1','-1'... ]

正如您所看到的,它只保存每行的第一个值,只保留第一个空格分隔的字符串:

with open('testing', 'r') as y:
    originalList = [line.strip().split()[0] for line in y]
如果希望值是整数,而不是字符串,那么当然

    originalList = [int(line.strip().split()[0]) for line in y]