简体   繁体   English

有没有办法在Python中循环遍历列表的子部分

[英]Is there a way to loop through a sub section of a list in Python

So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it? 因此,对于包含1000个元素的列表,我想从400循环到500.你是如何做到的?

I don't see a way by using the for each and for range techniques. 我没有看到使用for each和for range技术的方法。

for x in thousand[400:500]:
    pass

If you are working with an iterable instead of a list, you should use itertools : 如果您正在使用iterable而不是列表,则应使用itertools

import itertools
for x in itertools.islice(thousand, 400, 500):
    pass

If you need to loop over thousand[500] , then use 501 as the latter index. 如果你需要循环超过thousand[500] ,那么使用501作为后一个索引。 This will work even if thousand[501] is not a valid index. 即使thousand[501]不是有效索引,这也会有效。

for element in allElements[400:501]:
     # do something

These are slices and generate a sublist of the whole list. 这些是切片并生成整个列表的子列表。 They are one of the main elements of Python. 它们是Python的主要元素之一。

Using 运用

for element in allElements[400:501]:
    doSomething(element)

makes Python create new object, and might have some impact on memory usage. 使Python创建新对象,并可能对内存使用产生一些影响。

Instead I'd use: 相反,我会使用:

for index in xrange(400, 501):
    doSomething(allElements[index])

This way also enables you to manipulate list indexes during iteration. 这种方式还允许您在迭代期间操作列表索引。

EDIT: In Python 3.0 you can use range() instead of xrange() , but in 2.5 and earlier versions range() creates a list while xrange() creates a generator, which eats less of your precious RAM. 编辑:在Python 3.0中,您可以使用range()而不是xrange() ,但在2.5及更早版本中, range()创建一个列表,而xrange()创建一个生成器,它占用较少的宝贵RAM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM