簡體   English   中英

如何將字符串文件導入列表列表?

[英]How can I import a string file into a list of lists?

基本上我有一個文本文件:

-1  2  0  
 0  0  0  
 0  2 -1  
-1 -2  0   
 0 -2  2   
 0  1  0   

我希望將其放入列表列表中,如下所示:

[[-1,2,0],[0,0,0],[0,2,-1],[-1,-2,0],[0,-2,2],[0,1,0]]

到目前為止,我有這個代碼,但它會在列表中生成一個字符串列表。

import os  
f = open(os.path.expanduser("~/Desktop/example board.txt"))  
for line in f:  
    for i in line:  
        line = line.strip()  
        line = line.replace(' ',',')  
        line = line.replace(',,',',')  
        print(i)
        print(line)  
    b.append([line])  

那產生[['-1,2,0'],['0,0,0'],['0,2,-1'],['-1,-2,0'],['0,-2,2'],['0,1,0']]這幾乎是我想要的,除了引號。

我建議只使用numpy而不是重新發明輪子......

>>> import numpy as np
>>> np.loadtxt('example board.txt', dtype=int).tolist()
[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]

注意:根據您的需要,您可能會發現numpy數組是一個比列表列表更有用的數據結構。

使用csv模塊:

import csv

with open(r'example board.txt') as f:
    reader = csv.reader(f, delimiter='\t')
    lines = list(reader)

print lines

這應該可以解決問題,因為看起來您希望數據是數字而不是字符串:

fin = open('example.txt','r')
# The list we want
list_list = []
for line in fin:
    # Split the numbers that are separated by a space. Remove the CR+LF.
    numbers = line.replace("\n","").split(" ")
    # The first list
    list1 = []
    for digit in numbers:
        list1.append(int(digit))

    # The list within the list
    list_list.append(list1)

fin.close()

這會產生如下輸出:

[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]

簡單的解決方案,沒有其他庫

import os

lines = []
f = open(os.path.expanduser("~/Desktop/example board.txt"))
for line in f:
    x = [int(s) for s in line.split()]
    lines.append(x)

輸出:

[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]

如果你有逗號分隔值, csv模塊通常是你最好的選擇。 如果這不合適,無論出於何種原因,那么只需使用字符串和列表內置函數就可以實現它。

你可以在列表理解中完成整個事情:

with open('~/Desktop/example board.txt', 'r') as fin:
    lines = [[int(column.strip()) for column in row.split(',')] for row in fin]

但那是不透明的,可能會被重構:

def split_fields(row):
    fields = row.split(',')
    return [int(field.strip()) for field in fields]       

with open('~/Desktop/example board.txt', 'r') as fin:
    lines = [split_fields(row) for row in fin]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM