I'm trying to write a class which works in the same way as the cycle from itertools module but has some additional functionality. I want to have possibility to remove elements from a list along which I'm iterating.
Here is my code:
class myCycle(object):
def __init__(self, list):
self.list = list
def __iter__(self):
def iter(self):
while True:
if not self.list:
break
for e in self.list:
yield e
return iter(self)
def remove(self, e):
self.list.remove(e)
It works fine with one exception. Let's look at example:
>>> for i in c:
... print i
... if i == 1:
... c.remove(1)
... if i == 3:
... break
...
1
3
>>>
After removing 1 from the list, index move and that is probably reason why I don't have 2 in my output.
But how can I get it working? Or maybe there is some other way to get this functionality?
EDIT:
After your comments I will try to explain what I'm trying to do.
I have a string with player actions which can look like this one:
actions = "sBcffcffcfrfccc"
It's from poker, action f mean fold, c call and so one. Most interesting for us is fold.
And I also have list of players:
players = ['Saxum', 'Erasmus', 'Anders', 'Ginger', 'Adam',
'Crusoe', 'OgoPogo', 'Hari', 'Sanja', 'Hooke']
And I want to assign action to each player. So we are going through actions and players:
Saxum -> s
Erasmus -> B
Anders -> c
Ginger -> f
Ginger folded, we should remove this player. So how player list look like now:
players = ['Saxum', 'Erasmus', 'Anders', 'Adam',
'Crusoe', 'OgoPogo', 'Hari', 'Sanja', 'Hooke']
Adam -> f
Adam folded, we should remove this player. So how player list look like now:
players = ['Saxum', 'Erasmus', 'Anders',
'Crusoe', 'OgoPogo', 'Hari', 'Sanja', 'Hooke']
Crusoe -> c
OgoPogo -> f
OgoPogo folded, we should remove this player. So how player list look like now:
players = ['Saxum', 'Erasmus', 'Anders',
'Crusoe', 'Hari', 'Sanja', 'Hooke']
Hari -> f
Hari folded, we should remove this player. So how player list look like now:
players = ['Saxum', 'Erasmus', 'Anders',
'Crusoe', 'Sanja', 'Hooke']
Sanja -> c
Hooke -> f
Hooke folded, we should remove this player. So how player list look like now:
players = ['Saxum', 'Erasmus', 'Anders',
'Crusoe', 'Sanja']
Hooke was last on the list, so we start from beginning.
Saxum -> r
Erasmus -> f
Erasmus folded, we should remove this player. So how player list look like now:
players = ['Saxum', 'Anders',
'Crusoe', 'Sanja']
Anders -> c
Crusoe -> c
Sanja -> c
And that was reason why I started to implement myCycle. But maybe there is better way to do this?
Don't remove the items that are gone from the list -- replace them with None instead:
class MyCycle(object):
def __init__(self, lst):
self.list = lst
def __iter__(self):
while True:
items_left = False
for x in self.list:
if x is not None:
items_left = True
yield x
if not items_left:
return
def remove(self, e):
self.list[self.list.index(e)] = None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With