如何从txt文件创建列表列表

时间:2013-10-09 15:29:09

标签: python list python-3.x

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

我该怎么办?

感谢您的关注!

3 个答案:

答案 0 :(得分: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关键字。

答案 1 :(得分:1)

with open("data.txt","r") as fh:
    data = [ [float(x), float(y)] for x,y in line.split() for line in fh ]

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

data = [ list(map(float, line.split())) for line in fh ]

答案 2 :(得分:0)

这可能会:

LofL = []
with open("path", "r") as txt:
    while True:
        try:
            LofL.append(txt.readline().split(" "))
        except:
            break