python - 如何将枚举整数保存到空列表?
问题描述
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 )
我只需要存储所有行号,以便我可以编写一些逻辑来根据某些信息的位置拆分文件中的数据
解决方案
将索引存储在列表的字典中,其中键是您要查找的内容,值是索引列表
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]
}
这样,您实际上可以在一个地方跟踪多个查找或键,以备不时之需。
推荐阅读
- mysql - MySQL:如何用某个点的半径/中心构建多边形?
- javascript - 我怎样才能使这个脚本只在特定的屏幕尺寸以上执行?
- c# - 如何通过 Xamarin.Forms 中另一个选择器的选定项过滤选择器?
- java - 如何去除操作栏下的阴影
- python-3.x - 使用while循环的帕斯卡数
- postgresql - 如何使用 shell 脚本在 postgresql 中执行过程调用?
- html - 如何在较小的屏幕上重新定位一些块?
- sql - 从存储过程获取记录时出错
- docker - 如何使用 Docker 为开发和生产设置单独的 .env
- c# - 如何以编程方式获取 TabControl 的子项