python:我怎么知道我什么时候进入最后一个循环 [英] python: how do i know when i am on the last for cycle

查看:61
本文介绍了python:我怎么知道我什么时候进入最后一个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的 if 语句正在检查我是否在最后一个循环中,但它不起作用.我做错了什么?

解决方案

为了稍微避免这个问题,你似乎重写了 str.join:

','.join(results_histogram)

如果你得到类似TypeError: sequence item 0: expected string, int found这样的错误,那么你可以用

将中间结果转换成字符串

','.join(map(str, results_histogram))

<小时>

str.join 无疑比在循环中连接多个字符串更有效,因为在 Python 中,字符串是不可变的,所以每次连接都会导致创建一个新字符串,然后必须稍后收集垃圾.

<小时>

特别地,您的示例不起作用",因为当您只想跳过添加逗号时,您完全跳过了最后一个元素.举个小例子就很清楚了:

<预><代码>>>>x = [1,2,3]>>>对于范围内的 i(len(x)):...如果我 != len(x) - 1:... 打印 str(x[i]) + ',',...1, 2,

所以你可以重写你的例子

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

但你仍然应该坚持使用 str.join.

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?

解决方案

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.

这篇关于python:我怎么知道我什么时候进入最后一个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆