简体   繁体   English

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

[英]How to split numbers in a file by lines, and assign the lines into new lists?

How to split numbers in a file by lines, and assign the lines into new lists? 如何按行拆分文件中的数字,并将行分配到新列表中?

For example, 例如,
(numbers below are in a file) (下面的数字在文件中)

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

I want to make it 我想成功

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

This is untested, but you would do something similar to the following. 这是未经测试的,但您可以执行与以下类似的操作。

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

Remember that list is now a list of lists of string elements representing the numbers on each line. 请记住, list现在是表示每行数字的字符串元素列表的列表。 You'll have to do type conversion when accessing these elements to get an actual number (use something like int(list[list_index][number_index]) ). 在访问这些元素以获取实际数字时,您必须进行类型转换(使用类似int(list[list_index][number_index]) )。

try: 尝试:

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]]

You didn't mention if you cared that the output will remains a string, so this is the easiest IMO: 你没有提到你是否关心输出仍然是一个字符串,所以这是最容易的IMO:

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

This is tested: 经测试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM