To avoid the question slightly, you seem to have rewritten str.join
:
','.join(results_histogram)
If you get an error like TypeError: sequence item 0: expected string, int found
, then you can convert the intermediate results to a string with
','.join(map(str, results_histogram))
str.join
is undoubtedly more efficient than concatenating multiple strings in a loop, because in Python, strings are immutable, so every concatenation results in the creation of a new string, which then has to be garbage collected later.
Specifically, your example is "not working" because you skip the last element entirely, when you only want to skip adding the comma. This is clear and obvious with a small example:
>>> x = [1,2,3]
>>> for i in range(len(x)):
... if i != len(x) - 1:
... print str(x[i]) + ',',
...
1, 2,
So you could rewrite your example as
for i in range(len(results_histogram)):
url += str(results_histogram[i])
if i!=len(results_histogram)-1:
url += ','
But you should still stick with str.join
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…