我试图编写一个类,它的工作方式与itertools模块中的cycle相同,但有一些附加的功能。我希望有可能从我正在迭代的列表中删除元素。在
这是我的代码:
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)
它工作得很好,只有一个例外。让我们看看示例:
^{pr2}$从列表中删除1后,索引会移动,这可能是我的输出中没有2的原因。在
但是我怎样才能让它工作呢?或者有其他方法来实现这个功能?在
编辑:
在你的评论之后,我会尽力解释我想做什么。在
我有一个带玩家动作的字符串,看起来像这样:
actions = "sBcffcffcfrfccc"
它来自扑克,动作f平均折叠,c呼叫等等。对我们来说最有趣的是折叠。在
我还有球员名单:
players = ['Saxum', 'Erasmus', 'Anders', 'Ginger', 'Adam',
'Crusoe', 'OgoPogo', 'Hari', 'Sanja', 'Hooke']
我要给每个玩家分配动作。因此,我们将介绍动作和玩家:
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
这就是我开始实施我的循环的原因。但也许有更好的方法?在
您可以使用
while
循环:现在,正如你在对你的问题的评论中所指出的,你可能会找到一个更优雅的解决方案来解决你的问题。在
不要删除列表中已删除的项,请将其替换为
None
:事实上,这是可以通过手工制作迭代器而不是使用生成器函数来实现的。在
相关问题 更多 >
编程相关推荐