Python:for 循环 - for i in range(0,len(list) vs for i in list [英] Python: for loops - for i in range(0,len(list) vs for i in list

查看:62
本文介绍了Python:for 循环 - for i in range(0,len(list) vs for i in list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的 Python 力学问题.为什么我不能只说 for i in range original_list 而不是 for i in range(0, len(original_list)).人们通常使用范围而不是前者吗?谢谢!

# "如果我给你一个包含负数和正数的数组(即{3,2,-3,6,4,-7}),并让你对它进行排序,让负数先出现但是你没有改变剩余数字的相对顺序,你会怎么做?(即最终结果是{-3,-7,3,2,6,4}).原始列表 = [3, 2, -3, 6, 4, -7]pos_list = []neg_list = []对于范围内的 i(0, len(original_list)):如果 original_list[i] <0:neg_list.append(original_list[i])别的:pos_list.append(original_list[i])打印 neg_list + pos_list

解决方案

在您的情况下,由于您不需要使用列表中项目的索引,您可以使用 for in 对其进行迭代:

<预><代码>>>>对于 original_list 中的项目:...如果项目<0:……

如果要遍历列表中项目的索引,请使用 for in range(..):

<预><代码>>>>对于我在范围内(len(original_list)):...如果 original_list[i] <0:……

或者,您可能还想使用 enumerate() 如果你需要循环体中的项目和索引:

<预><代码>>>>对于我,枚举中的项目(原始列表):...如果项目<0:……

通过这种方式,您还消除了 original_list[i] 的使用.

This is a really simple python mechanics question. Why can't I just say for i in range original_list instead of for i in range(0, len(original_list)). Do people usually use range over the former? Thanks!

# "If I give you an array with negative and positive numbers (i.e. {3,2,-3,6,4,-7}) and asked you to sort it so that the negative numbers appeared first but you didn't change the relative order of the remaining numbers, how would you do it? (i.e. the final result would be {-3,-7,3,2,6,4}).

original_list = [3, 2, -3, 6, 4, -7]
pos_list = []
neg_list = []

for i in range(0, len(original_list)):
    if original_list[i] < 0:
        neg_list.append(original_list[i])
    else:
        pos_list.append(original_list[i])

print neg_list + pos_list

解决方案

In your case, since you don't need to use the index of the items in the list, you can just iterate over it using for in:

>>> for item in original_list:
...     if item < 0:
...         ...

If you want to iterate over the indexes of items in your list, use for in range(..):

>>> for i in range(len(original_list)):
...     if original_list[i] < 0:
...         ...

Alternatively, you might also want to use enumerate() if you need both item and index in loop's body:

>>> for i, item in enumerate(original_list):
...    if item < 0:
...        ...

By this way, you also eliminate the use of original_list[i].

这篇关于Python:for 循环 - for i in range(0,len(list) vs for i in list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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