我正在尝试编写一个类,它的工作方式与 itertools 模块中的循环相同,但具有一些附加功能。我希望有可能从我正在迭代的列表中删除元素。
这是我的代码:
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)
它工作正常,但有一个异常(exception)。让我们看一个例子:
>>> for i in c:
... print i
... if i == 1:
... c.remove(1)
... if i == 3:
... break
...
1
3
>>>
从列表中删除 1 后,索引移动,这可能是我的输出中没有 2 的原因。
但是我怎样才能让它工作呢?还是有其他方法可以获得此功能?
编辑:
在您发表评论后,我将尝试解释我正在尝试做的事情。
我有一个包含玩家 Action 的字符串,看起来像这样:
actions = "sBcffcffcfrfccc"
它来自扑克,行动 f 意味着弃牌,c 跟注等等。对我们来说最有趣的是弃牌。
我还有玩家列表:
players = ['Saxum', 'Erasmus', 'Anders', 'Ginger', 'Adam',
'Crusoe', 'OgoPogo', 'Hari', 'Sanja', 'Hooke']
我想为每个玩家分配 Action 。所以我们正在经历 Action 和玩家:
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
这就是我开始实现 myCycle 的原因。但也许有更好的方法来做到这一点?
请您参考如下方法:
不要删除已从列表中消失的项目——将它们替换为 None:
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
