-3

我正在使用 Python 3.3.2。现在我正在尝试从 txt 文件创建列表列表。例如:

我有一个包含这些数据的 txt 文件:

361263.236 1065865.816
361270.699 1065807.970
361280.158 1065757.748
361313.821 1065761.301

我希望 python 从此 txt 文件生成列表列表,所以我需要数据看起来像这样:[[102547.879, 365478.456], [102547.658, 451658.263], [102658.878, 231456.454]]

我必须做什么?

感谢您的关注!

4

3 回答 3

2

我鼓励with在新程序员中使用该语句,这是一个好习惯。

def read_list(filename):
    out = []
    # The `with` statement will close the opened file when you leave
    # the indented block
    with open(filename, 'r') as f:
        # f can be iterated line by line
        for line in f:
            # str.split() with no arguments splits a string by
            # whitespace charcters.
            strings = line.split()
            # You then need to cast/turn the strings into floating
            # point numbers.
            floats = [float(s) for s in strings]
            out.append(floats)
    return out

根据文件的大小,您也可以不使用out列表,而是修改它以使用yield关键字。

于 2013-10-09T15:55:26.877 回答
1
with open("data.txt","r") as fh:
    data = [ [float(x), float(y)] for x,y in line.split() for line in fh ]

这是我认为map更具可读性的情况,尽管必须将其包装list在 Python 3.x 中的调用中会减损它。

data = [ list(map(float, line.split())) for line in fh ]
于 2013-10-09T15:56:57.657 回答
0

这可能会:

LofL = []
with open("path", "r") as txt:
    while True:
        try:
            LofL.append(txt.readline().split(" "))
        except:
            break
于 2013-10-09T15:43:16.373 回答