Python中的多值变量

时间:2018-11-26 20:20:27

标签: python python-3.x

是否可以将多个值分配给一个变量? 我正在编写纸牌游戏,并通过KING使用ACE的值作为卡。有什么办法为变量分配“ ACE”的值和“ 1”的值,依此类推,KING为“ 13”?这不是必需的,但是会使代码更简单,更容易创建。


谢谢大家,我目前有这个:

from collections import namedtuple
Card = namedtuple('Card', 'name value')
ace = Card(name="ACE", value=1)

当我做print(ace)时,我会得到:Card(name="ACE", value=1),当我做ace.name或ace.value时,我也会得到正确的结果。

有什么办法可以在列表中具有“ ace”值,而仅撤消名称?

3 个答案:

答案 0 :(得分:4)

您可以使用类或namedtuple来包装两条数据

from collections import namedtuple

Card = namedtuple('Card', 'name value')
ace = Card(name="ACE", value=1)
king = Card(name="King", value=13)

自定义类可能会更好,因为这样您就可以实现card1 < card2

之类的逻辑
  

我可以使语句stackA + 1 == stackB为真吗?

是的,如果您在Card类型上实现了__radd____eq__方法,这些方法接受将其他Card添加到int类型并将结果与​​其他Card类型进行比较

答案 1 :(得分:3)

使用字典。

{'ace' :1, 'two' :2', ...etc}

答案 2 :(得分:0)

您可以使用自定义类:

class Card(object):
    # fancier output
    s = {0:"hearts", 1:"diamonds", 2:"clubs", 3:"spades"}
    r = {i:v for i,v in enumerate( [ "Ace","2","3","4","5","6","7","8",
                                     "9","10","Jack","Queen","King"],1)}
    def __init__(self, suit,rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        return "{} of {}".format(Card.r[self.rank],Card.s[self.suit])

    def __repr__(self):
        return str(self)

    def __lt__(self,other):
        return (self.suit,self.rank) < (other.suit, other.rank)


    @classmethod
    def summ_hand(cls,hand):
        return sum ( 10 if card.rank > 10 else card.rank for card in hand)


class Deck(object): 
    def __init__(self):
        self.cards = [Card(suit,rank) for suit in range(4) for rank in range(1,14)]


deck = Deck()

print( deck.cards )

输出:

[Ace of hearts, 2 of hearts, 3 of hearts, 4 of hearts, 5 of hearts, 6 of hearts, 
 7 of hearts, 8 of hearts, 9 of hearts, 10 of hearts, Jack of hearts, Queen of hearts, 
 King of hearts, 
 Ace of diamonds, 2 of diamonds, 3 of diamonds,4 of diamonds,5 of diamonds, 6 of diamonds, 
 7 of diamonds, 8 of diamonds, 9 of diamonds, 10 of diamonds, Jack of diamonds, 
 Queen of diamonds, King of diamonds, 
 Ace of clubs, 2 of clubs, 3 of clubs, 4 of clubs, 5 of clubs, 6 of clubs, 7 of clubs, 
 8 of clubs, 9 of clubs, 10 of clubs, Jack of clubs, Queen of clubs, King of clubs, 
 Ace of spades, 2 of spades, 3 of spades, 4 of spades, 5 of spades, 6 of spades, 
 7 of spades, 8 of spades, 9 of spades, 10 of spades, Jack of spades, Queen of spades, 
 King of spades]

提供__lq__(self)可让您排序:

hand = random.choices(deck.cards, k=7)
print(hand)
print(sorted(hand))

print( Card.summ_hand([Card(0,9),Card(0,11),Card(0,13)]))

输出:

# as given by choices
[Ace of hearts, Ace of spades, Queen of diamonds, 9 of spades, 
 King of hearts, Ace of spades, 3 of diamonds]

 # sorted
[Ace of hearts, King of hearts, 3 of diamonds, Queen of diamonds,
 Ace of spades, Ace of spades, 9 of spades]

29  # summ_hand for 9,Queen,King,