Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

syntax - python: how do i know when i am on the last for cycle

for i in range(len(results_histogram)):
    if i!=len(results_histogram)-1:
      url+=str(results_histogram[i])+','

my if statement is checking whether i am on the last loop, but it is not working. what am i doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...