从对中获取另一个元素

时间:2015-06-16 22:53:11

标签: python list python-3.x

如果我知道另一个元素,如何从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方法。但它并不那么有趣。

有没有漂亮的方法呢?

8 个答案:

答案 0 :(得分:4)

对于找到一对中的其他元素的任务,我只是写一个漂亮而清晰的函数:

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)

答案 1 :(得分:2)

您可以利用True可用作索引1的事实

>>> l = ['a','b']
>>> l['a' is l[0]]
'b'
>>> l['b' is l[0]]
'a'

因此您可以将您的功能定义为

def find(l,i):
    return l[i is l[0]]

演示

>>> find(["Player1","Player2"],"Player1")
'Player2'
>>> find(["Player1","Player2"],"Player2")
'Player1'

答案 2 :(得分:1)

当您想要更换玩家并获取第一个元素时,只需交换,然后您就不必关心谁是活跃的,因为每次都会得到一个不同的玩家:

players = ["playerA", "playerB"]

players[0],players[1] = players[1],players[0]

active = players[0]

或者更好,因为minitech只是致电list.reverse

  players = ["playerA", "playerB"]
  players.reverse()
  active = players[0]
  print(active)
  playerB

答案 3 :(得分:1)

使用set;

players = {playerA, playerB}
active_player = {playerA}

active_player = players - active_player  

或;

players = {playerA, playerB}
active_player = playerA

active_player = (players - {active_player}).pop()  

答案 4 :(得分:0)

这是切换标记的常用方法:

if active_player == playerA:
    active_player = playerB
else:
    active_player = playerA

答案 5 :(得分:0)

更好的解决方案是拥有一台发电机。

players = ['sdf','asdf','sasd']
active = 'sdf'
temp_players = (player for player in players if player != active)
active = temp_players.next()
通过这种方式,您可以获得所有玩家的列表,并且每次都可以获得一名玩家。 如果你一次在一支球队中有多名球员,这也会更容易。

答案 6 :(得分:0)

我建议:

players = ['playerA', 'playerB']
def active_player(): return players[0]
print(active_player()) 
players.reverse()
print(active_player()) 

给出:

playerA
playerB

答案 7 :(得分:0)

# conditional expressions
active_player = players[0] if players[1] == active_player else players[1]

# negative index
active_player = players[players.index(active_player) - 1]