如果我知道另一个元素,如何从 Python 3 中的一对(2 个元素的列表)中获取一个元素?比如在回合制策略游戏中,我想调换玩家:
players = [playerA, playerB]
active_player = playerA
players_tmp = list(players)
players_tmp.remove(active_player)
active_player = players_tmp[0]
这段代码工作得很好,但是很丑。
当然,在这种特殊情况下,我总是可以存储事件玩家的索引(0 或 1),然后执行以下操作:
self._active_player = 1 - self._active_player
然后写@property方法。但这并不那么有趣。
有什么漂亮的方法吗?
最佳答案
为了找到一对中的另一个元素,我只需要编写一个漂亮而清晰的函数:
def other_of(pair, item):
a, b = pair
return a if item == b else b
…
active_player = other_of(players, active_player)
不过,如果它适用于您的情况,itertools.cycle
循环选项可能是更好的方法:
import itertools
player_rotation = itertools.cycle(players)
…
active_player = next(player_rotation)
关于python - 从对中获取另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30879608/