如何按行拆分文件中的数字,并将行分配到新列表中?

时间:2017-05-04 14:29:10

标签: python list split assign

如何按行拆分文件中的数字,并将这些行分配到新列表中?

例如,
(下面的数字在文件中)

2 56 39 4 
20 59 30 68 4
28 50 7 68 95 05 68

我想成功

List1=[2, 56, 39, 4]
List2=[20, 59, 30, 68, 4]
List3=[28, 50, 7, 68, 95, 05, 68 ]

4 个答案:

答案 0 :(得分:0)

这是未经测试的,但您可以执行与以下类似的操作。

list = []
with open(filename, 'r') as f:
    for line in f:
        list.append(line.split(" ")) # Split the space-delimited line into a list and add the list to our master list

请记住,list现在是表示每行数字的字符串元素列表的列表。访问这些元素以获取实际数字时,您必须进行类型转换(使用类似int(list[list_index][number_index])的内容)。

答案 1 :(得分:0)

尝试:

result = []
with open(filename) as f:
    for line in f:
        result.append(map(int, line.strip().split()))

print(result)

Output:
[[2, 56, 39, 4], [20, 59, 30, 68, 4], [28, 50, 7, 68, 95, 5, 68]]

答案 2 :(得分:0)

你没有提到你是否关心输出仍然是一个字符串,所以这是最简单的IMO:

with open('filename') as file:
    lines = [row.split() for row in f.read()]

答案 3 :(得分:0)

经过测试:

 with open('source.txt') as source:
     lines = [line.split() for line in source.readlines()]

Output:
[['2', '56', '39', '4'], ['20', '59', '30', '68', '4'], ['28', '50', '7', '68', '95', '05', '68']]