首页 > 解决方案 > 如何将枚举整数保存到空列表?

问题描述

1) 我有一个文本文件,里面有一些可能多次出现的键值(例如 '002' 或 '006' 或 '007'

2)我写了一些代码,找到行号,每次找到特定出现的“002”

3)代码有效,但最新的发现会覆盖之前的任何一个,所以我最终得到一个。因此,我需要将找到“002”的每个行号存储到一个列表中。

4)它正在杀死我,我似乎无法存储行号。请帮忙..

# this is my code that finds the line numbers where '002' occurs 

lookup2 = 'Issuer:    002'


with open("C:/Destin/help.txt") as myFile:
    for num2, line in enumerate(myFile, 1):
        if lookup2 in line:
            print ('found the last num2 at line:', num2)
            num2int = int(num2)

输出

在第 7 行找到最后一个 num2 在第 14 行找到最后一个 num2

进程以退出代码 0 结束


#this is my problematic code

lookup2 = 'Issuer:    002'

my_list = [0, 0, 0, 0, 0, 0, 0]

i = 0
while i < len(my_list):
    with open("C:/Destin/help.txt") as myFile:
        for num2, line in enumerate(myFile, 1):
            if lookup2 in line:
                my_list[i] = mylist.append(num2)
                i = i + 1

print( my_list )

我只需要存储所有行号,以便我可以编写一些逻辑来根据某些信息的位置拆分文件中的数据

标签: pythonlistpycharmenumerated

解决方案


将索引存储在列表的字典中,其中键是您要查找的内容,值是索引列表

from collections import defaultdict

d = defaultdict(list)

with open("C:/Destin/help.txt") as myFile:
for num2, line in enumerate(myFile, 1):
    if lookup2 in line:
        print ('found the last num2 at line:', num2)
        d[lookup2].append(int(num2))

你应该最终得到类似的东西:

d = {
    "002": [7, 14]
}

这样,您实际上可以在一个地方跟踪多个查找或键,以备不时之需。


推荐阅读