Python字符串格式化太慢

标签 python string formatting

我使用下面的代码来记录一个 map ,当它只包含零时它很快,但是一旦 map 中有实际数据,它就会变得慢得难以忍受......有什么办法可以更快地做到这一点?

log_file = open('testfile', 'w')
for i, x in ((i, start + i * interval) for i in range(length)):
    log_file.write('%-5d %8.3f %13g %13g %13g %13g %13g %13g\n' % (i, x,
        map[0][i], map[1][i], map[2][i], map[3][i], map[4][i], map[5][i]))

最佳答案

我建议您使用 cProfile 模块运行您的代码,并按照 http://docs.python.org/library/profile.html 中的说明对结果进行后处理。 .这将让您确切知道在调用 str.__mod__ 以进行字符串格式化以及在其他事情上花费了多少时间,例如编写文件和执行 __getitem__ 查找 map[0][i] 等。

关于Python字符串格式化太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2637530/

相关文章:

python - Numpy:可能更好的格式?

python - 从两个不同长度的列表( [2 * n] 和 [2 * m] )到 [ 3 * len(unique(n[0],m[0])) ] 的单个列表的列表理解

python - 将 CamelCase 导入为小写是否符合 PEP8?

python - Django 管理员加载页面的速度非常慢

c# - 在 C# 中将 2 个本地字符串 [] 添加到单个数组中

python - 从 numpy 数组中的每个字符串中提取第一个字母

c++ - std::wstring 长度

c# - 使用下面行而不是上面行的格式插入 Excel 行

c# - 如何在 DateTime WEB 类型的 DataTable 列中仅设置日期

python - 在 Python 中重新启动线程