首先,我回顾了quickly.for示例的c++风格迭代器:
//--- Iterating over vector with iterator.
vector<int> v;
. . .
for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
cout << *it << endl;
}
它是灵活的。很容易改变底层的容器类型。例如,您可能会在以后决定插入和删除的数量非常多,以至于列表比向量更有效。它还有许多有用的成员函数。向量的许多成员函数使用迭代器,例如,assign、insert或erase。此外,我们可以双向使用迭代器(如果支持),例如++,--。这对于解析像对象这样的流很有用。
python的问题是:1:目前python for循环语法不如c++ for灵活。2:当iter.end()没有更多的时候,python会抛出异常,而不是"it != next()“风格。这是不灵活的。
问题1:我上面的想法正确吗?
好的。我的问题来了,如何实现一个像c++迭代器一样强大的python迭代器?目前,python for循环语法不如c++ for灵活。我还找到了一些可能的解决方案,比如http://www.velocityreviews.com/forums/t684406-pushback-iterator.html。但它要求用户push_back一个东西,而不是询问迭代器--。
问题2:在python中实现双向迭代器最好的是什么?就像http://www.cplusplus.com/reference/std/iterator/BidirectionalIterator/一样。伪代码如下:
it = v.begin();
while( it!=v.end()) {
//do sth here
if (condition1)
++it;//suppose this iterator supports ++
if(condition2)
--it;//suppose this iterator supports --
}
其主要特点是: 1)双向,2)更简单的“结束”检查。"++“或"--”运算符或公共函数都无关紧要(它们在语义上没有区别)。
谢谢,
更新:我从答案中得到了一些可能的解决方案:
i = 0
while i < len(sequence): # or i < len and some_other_condition
star_it = sequence[i]
if condition_one(star_it):
i += 1
if condition_two(star_it):
i = max(i - 1, 0)
然而,与数组不同,列表的随机访问应该是O(n)。我认为python内部的"list“对象是使用类似链表的东西实现的。因此,这种while循环解决方案效率不高。然而,在c++中,我们有“随机迭代器”,“双向迭代器”。我应该如何获得更好的解决方案?谢谢。
发布于 2012-04-05 21:47:46
您可以使用python对象实现类似的C++方式:
class Iterable(object):
class Iterator(object):
def __init__(self, father, pos=0):
self.father = father
self.pos = pos
def __getitem__(self, pos=0):
return self.father[self.pos + pos]
def __setitem__(self, pos, value):
self.father[self.pos + pos] = value
def __iadd__(self, increment):
self.pos += increment
return self
def __isub__(self, decrement):
self.pos -= decrement
return self
def __ne__(self, other):
return self.father != other.father or self.pos != other.pos
def __eq__(self, other):
return not (self != other)
def begin(self):
return self.Iterator(self)
def end(self):
return self.Iterator(self, len(self))
class Vector(list, Iterable):
pass
v = Vector([54, 43, 32, 21])
counter = 0
it = v.begin()
print it, it[0]
while it != v.end():
counter += 1
print it[0]
if counter == 2:
it += 1; # suppose this iterator supports ++
if counter == 1:
it -= 1; # suppose this iterator supports --
it += 1
这将*it
替换为it[0]
(也类似于C++),并将it++
替换为it += 1
,但实际上它几乎保持不变。
但是,如果你这样做了,你就离开了Pythonic的方式;-)
https://stackoverflow.com/questions/10028693
复制相似问题