[英]Cycle elements in a python list at least once
So I have a simple piece of code:所以我有一段简单的代码:
class Player:
def __init__(self):
self.score = 0
players = [Player() for _ in range(10)]
Now I want to:现在我想:
from itertools import cycle
loop = cycle(players)
loop = filter(lambda player: player.score >= 0, loop)
I have a problem with these conditions and I don't know how to bite them.我对这些情况有疑问,我不知道如何咬它们。
Here's a solution using mostly itertools
.这是一个主要使用itertools
的解决方案。
import itertools
positive_players = lambda : filter(lambda player: player.score >= 0, players)
loop = itertools.cycle(positive_players())
if len(list(positive_players())) <= 1:
loop = positive_players()
if len(set([p.score for p in positive_players()])) <= 1:
loop = positive_players()
Some tests:一些测试:
Here's an alternative solution, using a generator.这是使用生成器的替代解决方案。
def loop_players(players):
inx = 0
positive_count = 0
positive_scores = set()
while True:
p = players[inx]
inx += 1
if p.score < 0:
continue
positive_count += 1
positive_scores.add(p.score)
yield p
if inx == len(players):
inx = 0
if positive_count < 2:
break
if len(positive_scores) < 2:
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.