How to make more expressive python iterators? as a C ++ iterator

Firstly, I am quickly looking through C ++ style iterators. For instance:

//--- Iterating over vector with iterator.
vector<int> v;
. . .
for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
    cout << *it << endl;
}

He is flexible. Easy to change basic container types. For example, later you may decide that the number of insertions and deletions is so large that the list will be more efficient than the vector. It also has many useful member functions. Many of the member functions for vector use iterators, for example, are assigned, inserted, or erased. Moreover, we can use an iterator (if supported) bidirectional, for example, ++, -. This is useful for analyzing a stream similar to objects.

Python problems: 1: Currently, python for loop syntax is less flexible than C ++. (well, safer) 2: instead of the style "it! = Iter.end ()", python will throw an exception if next () has no more. This is not flexible.

Question 1: Is my idea above correct?

OK This begs my question, how to implement a more powerful python iterator as powerful as C ++ iterators? The syntax for python for loop is currently less flexible than C ++ for. I also found some possible solutions, such as http://www.velocityreviews.com/forums/t684406-pushback-iterator.html . but it asks the user push_back, not asking iterator -.

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). , "list" python , . , . ++ " ", " ". ? .

+5
5

Python for - . , - .

, for, ++ . Python , ++.


, while:

it = iter(obj)

try:
    while True: # or some secondary break condition other than StopIteration
        star_it = next(it)
        if condition_one(star_it):
            star_it = next(it)
except StopIteration:
    pass # exhausted the iterator

, --it Python.

-, . , , - while:

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)

-, . , , - :

current = node
while current: # or any break condition
    if condition_one(current):
        current = current.next
    if condition_two(star_it):
        current = current.prev

, , , , , ​​ set dict. --it . , , - .

, , , , , , mydict.values(), tuple(myset), , , while next, , for.

+5

, :

  • . , , :

    for key, value in my_dict.iteritems():
        if conditiion(value):
            my_dict[key] = new_value
    

    enumerate():

    for index, item in enumerate(my_list):
        if condition(item):
            my_list[index] = new_item
    
  • , " ". , - , :

    def iter_with look_ahead(iterable, sentinel=None):
        iterable, it_ahead = itertools.tee(iterable)
        next(it_ahead, None)
        return izip_longest(iterable, it_ahead, fillvalue=sentinel)
    
    for current, look_ahead in iter_with look_ahead(tokens):
        # whatever
    
  • . reversed() , .

  • . :

    my_list = list(my_iterable)
    
+1

, ++ . , :

  • : v.end()
  • : std::for_each(end, begin, func);
  • : std::for_each(v0.begin(), v2.end(), func);

Python ( , ), , Python Range.

Range , ++ 11 range-for:

for (Object& o: range) {
}

, , , , , ++. , :

for (Object& o: slice(range, 2, 9)) {
}

slice [2, 9) Range.

, , (Python), . - , , , , .

0

++ python:

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] ( ++) it++ it += 1, .

, Pythonic, -)

0

, Python , , , .

0

All Articles