Python:将3个信息文件合并到一个或多个字典中

2024-05-16 19:58:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试找出如何使用一个字典,它可以与犯罪类型、受害者数量和zipcode相关联

我遇到的问题是我有三个文件要访问

  1. 与该犯罪相关的犯罪类型和数量
  2. 受害人的报告号码
  3. 报告编号与犯罪编号和zipcode

这个程序不能只使用列表,因为它需要很长时间才能运行。我对编码非常陌生,只在列表中工作过,对如何使用这三个文件并将它们合并到词典中有点困惑


Tags: 文件程序类型编码列表数量字典报告
1条回答
网友
1楼 · 发布于 2024-05-16 19:58:41

这听起来像是一个应该在数据库而不是内存中处理的问题。使用数据库将允许您将这些值中的每一个转储到一个表中并轻松地查询它们。如果出于某种原因需要数据一直在内存中,可以使用字典

我会这样分解逻辑:

使用report\u number、report\u number和zipcode遍历文件。将其存储在dict1={report_number: [offense_number, zipcode], report_number2: [offense_number2, zipcode2]}

遍历包含受害者和报告编号的文件,对旧的dict1kvp进行比较。您将获得旧的列表值,附加受害者值,并将新列表添加到新字典dict2中

代码可能是这样的。我还创建了一个报告编号列表,用于这个问题的第三部分

dict2 = {}
report_numbers = []

for line.split(',') in victimFile:
    report_number = line[0]
    victim = line[1]
    tempList = dict1.get(report_number)
    tempList.append(victim)
    report_numbers.append(report_number)
    dict2.update({report_number:tempList})

对于最后一个包含数字的文件,遍历报表中的每个值,并从dict2中获取值。然后在每个值内进行检查,以查看文件中的编号是否在该列表中。如果是这样的话,我们将重复上面的方法,把进攻类型和数量添加到列表中

dict3 = {}
for line.split(',') in offenseFile:
    for report_number in report_numbers:
        offenseNumber = line[0]
        offenseType = line[1]
        tempList = dict.get(report_number)
        if offenseNumber in tempList:
            tempList.append(offenseNumber)
            tempList.append(offenseType)
            break
    dict3.update({report_number: tempList})

再说一遍

我要说的是数据库,上面的解决方案并不完美

相关问题 更多 >