Python将文件解析为列表列表字典: for loop is only appending last line

标签 python for-loop append fileparsing

我正在尝试解析具有一致格式的文件:标题和按间距分割的几行文本。 我想当一行有一个值时启动一个新的字典键,将以下行读入列表列表中,每个列表都是拆分词。 我首先尝试使用this尝试让程序识别新标记并使用索引计数器设置新 key 。 然后我最初使用 this相应地分割线。

这是我的代码当前的样子:

import sys

def openfile(file):
    frames = {}
    index = 0
    with open(file, 'r') as f:
        for line in f:
            if line.strip() == '5310':
                index +=1
            else:
                newline = line
                print newline
                frames[index] = []
                frames[index].append([newline.split()])
        print frames

openfile(sys.argv[1])

索引将正确计数,并且“打印换行符”正在打印我想要的所有行,但最终打印的字典是一个嵌套列表:

{1:[['last', 'line', 'of', 'input', 'file']]}

我想要的是:

{1:[[line1],[line2] ...], 2:[[nextline], [nextline] ...], ... , key n : [[line], [line]....[lastline]]}

我也尝试过:

def openfile(file):
    frames = {}
    index = 0
    with open(file) as f:
         for line in f:
            if str(line.strip()) == '5310':
                index += 1
            else:
                frames[index] = []
                frames[index].append([line.split()])
    return frames

这也行不通。 这给我留下了两个问题: 1:为什么我当前的代码会打印但不会 append 我想要的行? 2.我还能尝试什么来让它发挥作用?

编辑 谢谢!我设法让它发挥作用。 如果有人遇到类似的问题,这是我的有效代码:

import sys

def openfile(file):
    frames = {}
    index = 0
    with open(file, 'r') as f:
        for line in f:
            if line.strip() == '5310':
                index +=1
                frames[index] = []
            else:
                newline = line
                print newline
                frames[index].append([newline.split()])
        print frames

openfile(sys.argv[1])

最佳答案

你的问题很明显......一旦你看到问题:-)

            frames[index] = []
            frames[index].append([newline.split()])

每次循环时,您都会清除之前的进度,并从一个新的空列表开始。因此,只有最后一次迭代的结果位于中。

初始化代码只需在进入循环之前完成一次。

with open(file) as f:
     frames[index] = []
     for line in f:

...或其他适合您应用程序的点。

关于Python将文件解析为列表列表字典: for loop is only appending last line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51069334/

相关文章:

python - Django 的 FilteredSelectMultiple 小部件仅在登录时才起作用

python - 基于字典中的一个键的字典列表中的一个值的总和

python - python中的递归代码

python - 覆盖pytest中的子 fixture

python - 如何定义通过另一个函数内的 for 循环创建的全局变量?

for-loop - 打破 Julia 中的循环

python - 我将如何使用 .join 和 for 循环制作随机十六进制代码生成器?

java - 如何 append 变量 ID - AndroidX

Scala:如何 append 到 Seq

python - 如何将不同的元素添加到列表中的列表中? python 3