简体   繁体   English

python:迭代列表中的特定范围

[英]python: iterate a specific range in a list

Lets say I have a list:假设我有一个清单:

listOfStuff =([a,b], [c,d], [e,f], [f,g])

What I want to do is to iterate through the middle 2 components in a way similar to the following code:我想要做的是以类似于以下代码的方式遍历中间的 2 个组件:

for item in listOfStuff(range(2,3))
   print item

The end result should be as below:最终结果应如下所示:

[c,d]
[e,f]

This code currently does not work, but I hope you can understand what I am trying to do.这段代码目前不起作用,但我希望你能理解我在做什么。

listOfStuff =([a,b], [c,d], [e,f], [f,g])

for item in listOfStuff[1:3]:
    print item

You have to iterate over a slice of your tuple.您必须遍历元组的一部分。 The 1 is the first element you need and 3 (actually 2+1) is the first element you don't need. 1是您需要的第一个元素,而3 (实际上是 2+1)是您不需要的第一个元素。

Elements in a list are numerated from 0:列表中的元素从 0 开始编号:

listOfStuff =([a,b], [c,d], [e,f], [f,g])
               0      1      2      3

[1:3] takes elements 1 and 2. [1:3]采用元素 1 和 2。

A more memory efficient way to iterate over a slice of a list would be to use islice() from the itertools module:迭代列表切片的一种更内存有效的方法是使用itertools模块中的islice()

from itertools import islice

listOfStuff = (['a','b'], ['c','d'], ['e','f'], ['g','h'])

for item in islice(listOfStuff, 1, 3):
    print(item)

# ['c', 'd']
# ['e', 'f']

However, this can be relatively inefficient in terms of performance if the start value of the range is a large value since islice would have to iterate over the first start value-1 items before returning items.然而,如果范围的起始值是一个大值,这在性能方面可能相对低效,因为islice在返回项目之前必须迭代第一个起始值 - 1 的项目。

You want to use slicing.你想使用切片。

for item in listOfStuff[1:3]:
    print item

By using iter builtin:通过使用iter内置:

l = [1, 2, 3]
# i is the first item.
i = iter(l)
next(i)
for d in i:
    print(d)

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

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