如何从txt文件制作3D列表?蟒蛇

时间:2016-12-13 20:00:55

标签: python list

我已经被困在这3天了,我已经尝试了很多不同的方法,但都没有奏效!

txt文件(num.txt)如下所示:

1234
4321
3214
3321
4421
2341

如何将此文件放入由2行3列组成的3D列表中?

我想要实现的输出是:

[ [['1','2','3','4']['4','3','2','1']['3','2','1','4']], [['3','3','2','1']['4','4','2','1']['2','3','4','1']] ]

(为了让它更容易看到,我将它分开了一点!)

我认为它类似于制作2D列表,但我尝试过的任何工作都没有!有人可以帮忙吗?

谢谢!

4 个答案:

答案 0 :(得分:2)

使用一些简单的算法,这是一种非常简单的方法:

with open('num.txt') as infile:  # open file
    answer = []
    for i,line in enumerate(infile):  # get the line number (starting at 0) and the actual line
        if not i%3: answer.append([])
        answer[-1].append(list(line.strip()))

答案 1 :(得分:1)

您必须打开该文件并将每个字符串行类型转换为list,如:

my_list = []
sublist_size = 3

with open('/path/to/num.txt') as f:
    file_lines = list(f)
    for i in range(0, len(file_lines), sublist_size):
        my_list.append([list(line.rstrip()) for line in file_lines[i:i+sublist_size]])
        #                           ^ Remove `\n` from right of each line

此处my_list将保留您想要的值:

[[['1','2','3','4']['4','3','2','1']['3','2','1','4']],
 [['3','3','2','1']['4','4','2','1']['2','3','4','1']]]

答案 2 :(得分:1)

使用range()函数和简单列表理解的解决方案:

with open('./text_files/num.txt', 'r') as fh:  # change to your current file path
    l = [list(l.strip()) for l in fh]

n = 3   # chunk size
result = [l[i:i + n] for i in range(0, len(l), n)]  # splitting into chunks of size 3
print(result)

输出:

[[['1', '2', '3', '4'], ['4', '3', '2', '1'], ['3', '2', '1', '4']], [['3', '3', '2', '1'], ['4', '4', '2', '1'], ['2', '3', '4', '1']]]

答案 3 :(得分:0)

我认为另一个选项更清晰,不需要将整个文件加载到内存中:

inner_size = 3
inner_range = range(inner_size)  # precompute this since we'll be using it a lot
with open('/home/user/nums.txt') as f:
    result = []
    try:
        while True:
            subarr = []
            for _ in inner_range:
                subarr.append(list(f.next().rstrip()))
            result.append(subarr)
    except StopIteration:
        pass

使用文件对象上的内置__iter__,我们构建子数组并将它们附加到结果数组上,并使用StopIteration异常知道我们已完成,丢弃任何额外数据。如果你想在结尾保留任何部分子句,你可以轻松if subarr: result.append(subarr)

作为列表理解编写(虽然没有能力恢复任何最终的部分子列表):

inner_size = 3
inner_range = range(inner_size)
with open('/home/user/nums.txt') as f:
    result = []
    try:
        while True:
            result.append([list(f.next().rstrip()) for _ in inner_range])
    except StopIteration:
        pass