【问题标题】:Code is working slow - performance issue in python代码运行缓慢 - python 中的性能问题
【发布时间】:2021-11-05 06:40:30
【问题描述】:

我的文件有 4 列,其中包含分隔值。我只需要第一列,所以我已经读取了文件,然后将该行拆分、分隔并将其存储在一个名为 first_file_list 的列表变量中。

我有另一个文件,它有 6 列,带有分隔值。我的要求是读取文件第一行的第一列并检查字符串是否存在于名为 first_file_list 的列表中。如果存在,则将该行复制到新文件中。

我的第一个文件大约有。 600 万条记录和第二个文件大约有。 450 万条记录。只是为了检查我的代码的性能而不是 450 万,我只在第二个文件中放入了 100k 条记录,并且处理 100k 条记录代码大约需要。 2.5 小时。

以下是我的逻辑:

first_file_list = []

with open("c:\first_file.csv") as first_f:
    next(first_f)  # Ignoring first row as it is header and I don't need that
    temp = first_f.readlines()
    for x in temp:
        first_file_list.append(x.split(',')[0])
first_f.close()

with open("c:\second_file.csv") as second_f:
    next(second_f)
    second_file_co = second_f.readlines()
second_f.close()

out_file = open("c:\output_file.csv", "a")
for x in second_file_co:
    if x.split(',')[0] in first_file_list:
        out_file.write(x)
out_file.close()

您能否帮我了解一下我在这里做错了什么,以便我的代码花费这么多时间来比较 10 万条记录?或者您能建议在 Python 中执行此操作的更好方法吗?

【问题讨论】:

  • first_file_list 设为set,其中每个条目都是分隔字符串而不是list
  • 顺便说一句,使用with 语句意味着您不必在打开的文件对象上调用.close()
  • 你可以直接遍历文件(for x in first_f);无需先将整个文件读入内存。
  • “lac”是指“100,000”吗?
  • 我建议不要使用“Lac”或更准确地说是“lakh”,因为它在印度/某些地区之外并不为人所知。我喜欢英语,它是一门语言——请好好学习(顺便说一句,你还没有学过),你会很高兴你做到了。 :-)

标签: python python-3.x list file-comparison filecompare


【解决方案1】:

使用set 进行快速成员资格检查。 此外,无需将整个文件的内容复制到内存中。您可以遍历文件的剩余内容。

first_entries = set()
with open("c:\first_file.csv") as first_f:
    next(first_f)
    for line in first_f:
        first_entries.add(line.split(',')[0])

with open("c:\second_file.csv") as second_f:
    with open("c:\output_file.csv", "a") as out_file:
        next(second_f)
        for line in second_f:
            if line.split(',')[0] in first_entries:
                out_file.write(line)

此外,我注意到您在使用with 语句打开的文件对象上调用了.close()。使用with(上下文管理器)意味着在您退出其上下文后完成所有清理工作。所以它会为你处理.close()

【讨论】:

  • 只需 20 秒即可完成包含 450 万条记录的文件。 450 万 = 45,00,000
【解决方案2】:

使用集合 - 见下文

first_file_values = set()
second_file_values = set()

with open("c:\first_file.csv") as first_f:
    next(first_f)
    temp = first_f.readlines()
    for x in temp:
        first_file_values.add(x.split(',')[0])

with open("c:\second_file.csv") as second_f:
    next(second_f)
    second_file_co = second_f.readlines()
    for x in second_file_co:
        second_file_values.add(x.split(',')[0])

with open("c:\output_file.csv", "a") as out_file:
    for x in second_file_values:
        if x in first_file_values:
            out_file.write(x)

【讨论】:

  • 好新!你能解释一下Lakh是什么吗?
  • 450 万 = 45,00,000
猜你喜欢
  • 1970-01-01
  • 2022-08-20
  • 2018-09-16
  • 2014-11-28
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多