在列表中创建对象的两个副本

Creating two copies of objects in a list

我一直很想弄清楚这个问题,但我似乎无法让它发挥作用。

我有一个 class 叫做 Deck:

import random
class Deck(list):
'''
a list of cards represented in a deck
'''
def __init__(self):
    ''' a list of cards'''
    list.__init__(self)
    for i in range(52):
        self.append(Card(i))

def isEmpty(self):
    '''checks if Deck is empty or not; returns T or F'''
    return self(len) == 0

def shuffle(self):
    ''' shuffles the list of cards in random order'''
    return random.shuffle(self)

def deal(self, num):
    '''creates a new list of cards from the deck.
    Arguments:
        num = an integer to assign how many cards to deal
    Returns:
        a new list of cards taken from the deck
    '''
    new = []
    for i in range(num):
        x = self.pop(0)                    #something to note, if instead "x = self.pop(i)"
        new.append(x)                      #it will only take even card, and leave out odd cards
    return new

def restore(self, lst):
    '''restores the cards already taken from Deck
    Arguments:
        lst = a list of cards pulled out from Deck
    Returns:
        nothing; returns cards to the Deck
    '''
    while len(lst) > 0:
        x = lst.pop(0)
        self.append(x)

Class Deck 是对象 Cards 的列表,它派生自 class 称为 Card.

现在我必须创建一个名为 PinochleoDeck 的 class:

class PinochleDeck(Deck):

    def __init__(self):
        Deck.__init__(self)
        x = 0
        for i in range(4):
            for i in range(7):
                self.pop(x)
            x += 6

它应该只得到所有花色从 9 到 A 的套牌,即 24 张牌。 但我还必须将所有卡片制作两份,总共 48 张卡片,如 class PinochleoDeck。

我尝试了很多东西,例如 itertools、复制,甚至是粗略乘法,但其中 none 成功了。如何在不创建新列表的情况下制作列表中对象的两个副本,以便 class PinocheloDeck 有 48 张卡片?

谢谢

在我看来,您在第一次通过时只是删除了一些卡片。要获得所有 28 张卡片的一份副本,您需要在 PinochleDeck class 中添加一行。见下文:

class PinochleDeck(Deck):

    def __init__(self):
        Deck.__init__(self)
        x = 0
        for i in range(4):
            for i in range(7):
                self.pop(x)
                x += 1  #NEED TO INCREMENT EVERY TIME THROUGH!!!
            x += 6

要获得每个副本的两份,您可以这样做:

class PinochleDeck(Deck):

    def __init__(self):
        Deck.__init__(self)
        x = 0
        for i in range(4):
            for i in range(7):
                self.pop(x)
                x += 1  #NEED TO INCREMENT EVERY TIME THROUGH!!!
            x += 6
        self.extend(self)

现在,这仅在您不关心同一实例的多个副本时才有效(即您的牌不会改变,因此梅花 A 看起来总是完全一样)。如果您需要能够在不相互踩踏的情况下进行修改的副本,您将需要对每张卡片执行 deepcopy 或退出使用您的 Deck class 的 __init__。我会选择:

class PinochleDeck(Deck):

    def __init__(self):
        list.__init__(self)

        for i in range(2):
            for suit_ind in range(4):
                for card_ind in range(7, 13):
                    self.append(Card(suit_ind*card_ind))

如果您有卡片对象列表,则需要对列表进行深层复制:

 from copy import deepcopy

要将它们添加到原始列表,请使用扩展:

 your_list.extend(deepcopy(your_list))

你也不能调用自己self(len)