簡體   English   中英

如何按行拆分文件中的數字,並將行分配到新列表中?

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

如何按行拆分文件中的數字,並將行分配到新列表中?

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

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 ]

這是未經測試的,但您可以執行與以下類似的操作。

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

嘗試:

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

你沒有提到你是否關心輸出仍然是一個字符串,所以這是最容易的IMO:

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

經測試:

 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