【发布时间】:2017-05-05 15:10:52
【问题描述】:
如何在不导入任何函数的情况下减少嵌套循环的处理时间?我的程序非常快,但是编写矩阵需要很长时间。我尝试使用range
和我在网上找到的其他建议,但它仍然是一样的。
for i in matrix:
string = ''
for j in i:
if j not in path and j != 'N':
string += '_'
elif j in path and j != 'N':
string += '+'
else:
string += 'N'
f.write(string+"\n")
谢谢
【问题讨论】:
-
什么是
path?如果它可能是set,它应该可以更快地启动。 -
matrix和path包含什么?通过重复连接构建字符串通常很糟糕。非基于哈希的容器中的成员资格测试也很慢。 -
谢谢 zipa,是的,我使用了 set,它帮助很大
-
不要在循环中的字符串上使用
+=!它可能似乎很快,但it has trivial failure cases 通常不能依赖。列个清单并致电join,就像@tzaman 展示的那样。 -
嗨 Veedrac,非常感谢您让我知道!我有一个错误的印象是 += aString 更快,所以我几乎在我的每个程序中都使用它
标签: performance python-3.x for-loop matrix