从一个列表中取出并将它们放入另一个列表中(python)

时间:2013-07-26 18:18:38

标签: python list

我正在为我的第二次任务工作一些代码,在python中使用Go Fish游戏。对于我的一个函数定义,我需要从target_player列表中取出target_rank,并将其附加到当前玩家卡列表中。我尝试使用for循环,但收到错误以更改列表的长度。到目前为止,我的代码是

def Hit(player_number, target_player, target_rank, pHands):
    while str(target_rank) in pHands[target_player]:
       pHands[player_number].append(pHands[target_player].pop(target_rank))
    print pHands[player_number]
    print pHands[target_player]
pHands = [['a', '2', '3', '4', '4', '5', '6', '7', '7', 't'], ['2', 'q', '6', '9', '5', 'k', 'k', 'a', '3', '8'], ['j', '9', 't', 't', '2', 't', '7', 'j', '5', '9'], ['8', '8', 'a', 'q', 'k', '4', '6', '9', 'q', '2']]
Hit (0,1,'a',pHands)

其中pHands是球员卡列表。我明白我不能使用pop因为目标排名是一个字符串而不是地方价值,但任何帮助将非常感激。谢谢大家!

2 个答案:

答案 0 :(得分:3)

我认为不要将popappend链接起来可能会更清楚。此外,pop需要一个索引号,而不是卡值本身,所以在这里使用它有点尴尬。相反,您可以使用remove

def Hit(player_number, target_player, target_rank, pHands):
    while target_rank in pHands[target_player]:
        pHands[target_player].remove(target_rank)
        pHands[player_number].append(target_rank)
    print pHands[player_number]
    print pHands[target_player]

然而,pop and remove are O(n) operations。对pHands[target_player]中的每张卡执行一次即可while-loop O(n**2)。如果我们能够在O(n)中执行任务会更好,而append, which is an O(1) operation可以实现这一点。因此,如果append中的每张卡片都需要pHands[target_player]一次,那么for-loop(下方)就是O(n)

def Hit(player_number, target_player, target_rank, pHands):
    new_target_hand = []
    for card in pHands[target_player]:
        if target_rank == card:
            pHands[player_number].append(card)
        else:
            new_target_hand.append(card)
    pHands[target_player] = new_target_hand
    print pHands[player_number]
    print pHands[target_player]

答案 1 :(得分:1)

编辑:我的工作正常但THIS一个更清洁。

def Hit(player_number, target_player, target_rank, pHands):
    try:
        while True:
           pHands[player_number].append(pHands[target_player].pop(pHands.index(target_rank)))
        print pHands[player_number]
        print pHands[target_player]
    except ValueError:
        pass # value no longer in hand
pHands = [['a', '2', '3', '4', '4', '5', '6', '7', '7', 't'], ['2', 'q', '6', '9', '5', 'k', 'k', 'a', '3', '8'], ['j', '9', 't', 't', '2', 't', '7', 'j', '5', '9'], ['8', '8', 'a', 'q', 'k', '4', '6', '9', 'q', '2']]
Hit (0,1,'a',pHands)