操纵对象中的列表,这些列表再次位于列表中

时间:2015-10-15 04:25:25

标签: python list for-loop

我是学习python的新手(在大学里学到的第一种编程语言是C),并希望逐步编写一个小卡片游戏作为练习。更具体地讲,它是关于德州扑克游戏的。

我写了一个包含所有相关属性的课程cPlayer

class cPlayer(object):
    def __init__ (self, id=0, name='', hand=[], credit=1000):
        self.id=id
        self.name=name
        self.hand=hand
        self.credit=credit

然后我制作了一张扑克牌清单,并将其洗牌。

deck=[]
for i in range(0,4):
    for j in range(0,13):
        deck.append([value[j], suit[i]])
shuffle(deck)

此外,我有一个List,通过for循环填充6 cPlayer

list_of_players=[]    
for i in range(PLAYERS):
    x=cPlayer()
    x.id=i+1
    x.name=i+1
    for j in range(2):
        x.hand.append([0,0])
    list_of_players.append(x)

在第一步中,我只想给每个cPlayer一个hand,这是两张牌的列表,这两张牌再次列出两个值(value和{ {1}})。因此我写了一个函数:

suit

检查我做了一些打印功能的所有内容。相关的是这一个:

def deal_hole_cards():
    for i in range(2):
        for j in range(len(list_of_players)):
            list_of_players[j].hand[i]=deck.pop()

我现在得到的是这样的:

output

每个"玩家"在循环之后得到同一只手。不知何故,所有以前的手都被最后一次使用def print_hands(): print '==HANDS==' for i in range(len(list_of_players)): print dict_player[list_of_players[i].name] +' ', print_card(list_of_players[i].hand[0]) print_card(list_of_players[i].hand[1]) print '' 覆盖。这必须是一个参考问题。但是我该如何修复它,以便每个玩家拥有不同的牌?我用Google搜索并发现了一些类似的问题,但无法为我找到合适的解决方案。

注意:对于打印件,我通过可以正常工作的字典翻译卡片值和播放器名称。

1 个答案:

答案 0 :(得分:0)

如上所述,您不应在签名中使用mutable作为默认值,但这不是您的主要问题。我认为你没有正确解开这些值。您不应该追加,而是覆盖这些值。 在创建过程中,您应该设置默认值:

x.hand = [[0,0], [0,0]]
list_of_players.append(x)

当添加弹出套牌时,请使用此方法而不是追加:

for j in range(len(list_of_players)):
    list_of_players[j].hand = [deck.pop(),deck.pop()]

通过使用append,您引用了与您想象的相同的列表。

整个版本:

from random import shuffle

PLAYERS = 6

class cPlayer(object):
    def __init__ (self, id=0, name='', hand=[], credit=1000):
        self.id=id
        self.name=name
        self.hand=hand
        self.credit=credit


deck = []
for i in range(0,4):
   for j in range(0,13):
      deck.append([i,j])

shuffle(deck)

list_of_players = []
for i in range(PLAYERS):
    x=cPlayer()
    x.id=i+1
    x.name=i+1
    x.hand = [[0,0], [0,0]]
    list_of_players.append(x)


def deal_hole_cards():
    for j in range(len(list_of_players)):
        list_of_players[j].hand = [deck.pop(),deck.pop()]


deal_hole_cards()

for i in list_of_players:
    print i.id, i.hand

输出:

1 [[0, 12], [0, 7]]
2 [[3, 9], [1, 1]]
3 [[1, 6], [3, 3]]
4 [[3, 5], [2, 9]]
5 [[2, 3], [1, 5]]
6 [[1, 11], [2, 4]]

我知道我错过了unicode的东西,但这应该是微不足道的。