迭代列表切片 [英] Iteration over list slices

查看:107
本文介绍了迭代列表切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个算法迭代列表切片。切片大小设置在函数外部,可以有所不同。

I want an algorithm to iterate over list slices. Slices size is set outside the function and can differ.

在我看来,它是这样的:

In my mind it is something like:

for list_of_x_items in fatherList:
    foo(list_of_x_items)

有没有办法正确定义 list_of_x_items 或使用python 2.5执行此操作的其他方式?

Is there a way to properly define list_of_x_items or some other way of doing this using python 2.5?

edit1:澄清分区和滑动窗口这两个术语听起来都适用于我的任务,但我不是专家。所以我会更深入地解释这个问题并添加到问题中:

edit1: Clarification Both "partitioning" and "sliding window" terms sound applicable to my task, but I am no expert. So I will explain the problem a bit deeper and add to the question:

fatherList是一个多级的numpy.array我从一个文件中获取。函数必须找到系列的平均值(用户提供系列的长度)为了平均我使用 mean()函数。现在进行问题扩展:

The fatherList is a multilevel numpy.array I am getting from a file. Function has to find averages of series (user provides the length of series) For averaging I am using the mean() function. Now for question expansion:

edit2:如何修改您提供的用于存储额外项目的函数,并在下一个fatherList为时使用它们如果列表长度为10且块的大小为3,则列表的第10个成员被存储并附加到开头,例如,如果列表是长度10并且块的大小是3,那么它将被送到函数?

edit2: How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?

下一个清单。

  • What is the most "pythonic" way to iterate over a list in chunks?

推荐答案

< h3>回答问题的最后部分:

Answer to the last part of the question:


问题更新:如何修改你提供给商店的
函数
额外的项目,当
下一个fatherList被输入
函数时使用它们?

question update: How to modify the function you have provided to store the extra items and use them when the next fatherList is fed to the function?

如果你需要存储状态然后你可以使用一个对象。

If you need to store state then you can use an object for that.

class Chunker(object):
    """Split `iterable` on evenly sized chunks.

    Leftovers are remembered and yielded at the next call.
    """
    def __init__(self, chunksize):
        assert chunksize > 0
        self.chunksize = chunksize        
        self.chunk = []

    def __call__(self, iterable):
        """Yield items from `iterable` `self.chunksize` at the time."""
        assert len(self.chunk) < self.chunksize
        for item in iterable:
            self.chunk.append(item)
            if len(self.chunk) == self.chunksize:
                # yield collected full chunk
                yield self.chunk
                self.chunk = [] 

示例:

chunker = Chunker(3)
for s in "abcd", "efgh":
    for chunk in chunker(s):
        print ''.join(chunk)

if chunker.chunk: # is there anything left?
    print ''.join(chunker.chunk)

输出:

abc
def
gh

这篇关于迭代列表切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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