[英]Most efficient way to join strings in Python
During the interview, I was given a piece of Python code: 在采访中,我得到了一段Python代码:
"".join([x for x in "\x63\x6c\x75\x62"])
The interviewer asked me: Can you make this piece of code faster with just a tiny tweak to the existing code? 面试官问我:您能否通过对现有代码进行一些细微调整来使这段代码更快? The output should stay exactly the same. 输出应保持完全相同。
Enough to say, I failed this question. 可以说,我没有通过这个问题。 I'm wondering if anything could help me understand how to optimize this code? 我想知道是否有什么可以帮助我理解如何优化此代码的?
Thanks a lot. 非常感谢。
"".join([x for x in "\x63\x6c\x75\x62"])
is a very redundant way of doing: 是一种非常多余的方式:
"\x63\x6c\x75\x62"
In general, you should not do 一般来说,您不应该这样做
x for x in "\x63\x6c\x75\x62"
this is useless because you don't transform or filter x
in any way (and it's of course slower). 这是没有用的,因为您不会以任何方式变换或过滤x
(并且当然会变慢)。
One last thing, if the interviewer meant to remove the []
he/she was also wrong. 最后一件事,如果面试官打算删除[]
/ []
他/她也是错误的。
"".join(x for x in "\x63\x6c\x75\x62")
is slower that with the listcomp because join
has to build a list
anyway (useful to remember this when creating useful comprehension, unlike that one, see Joining strings. Generator or list comprehension? ) 与 listcomp相比,它要慢一些,因为join
无论如何都必须建立一个list
(在创建有用的理解时记住这一点很有用, 与之不同的是,请参阅连接字符串。生成器还是列表理解? )
Conclusion: let's not join the club
结论:我们不要加入club
Nothing to do: 没事做:
>>> res = "\x63\x6c\x75\x62"
>>> res
'club'
It just a different way to enter the sting. 这只是进入the的另一种方式。
好的,这个版本呢?
"".join(* ["\x63\x6c\x75\x62"])
%%timeit
"".join([x for x in "\x63\x6c\x75\x62"])
289 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Outputs club
. 输出club
。
%%timeit
"".join(["\x63\x6c\x75\x62"])
66.8 ns ± 0.46 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
Outputs club
. 输出club
。
[x for x...] is useless here. [x代表x ...]在这里没有用。 Removing it makes the code running 4 times faster. 删除它可使代码运行快4倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.