脚本写字典并将其写入文件然后加载

时间:2019-02-16 14:56:51

标签: python arrays dictionary enums

编辑:由于无法指出我的问题,因此我重新整理了整个帖子并实现了我的实际代码。感谢大家的贡献,我希望这个版本更加清晰。

我的目标是对扑克手范围进行大量评估(例如,我有TT,而您有AA,KK或AK)。因此,将有两个输入字符串“ TT”和“ AA,KK,AK”。 这些字符串被分成各个部分(“ AA”,“ KK”,“ AK”),然后用作我的字典中的键。该字典的结构为key:array((card,card),...)对象。

下面是创建字典并将其写入文件的代码。虽然在上部创建的字典可以正常工作,但我无法将其导出到文件中,以后再将其导入另一个程序而不会出现语法/名称错误。

from enum import Enum #need python 3.4
import operator
from random import shuffle


class CardValue(Enum):  #name = value
    A = 14
    K = 13
    Q = 12
    J = 11
    T = 10
    N = 9
    E = 8
    S = 7
    F = 6

    def __str__(self):
        if self.value > 9:
            return "{}".format(self.name)
        else:
            return "{}".format(str(self.value))

class CardSuit(Enum):
    c = 1
    d = 2
    h = 3 
    s = 4

    def __str__(self):
        return "{}".format(self.name)

class Card(tuple):    #tuples are unchangable

    def __new__(cls, value, suit):    #new is immutable
        assert isinstance(value, CardValue)    #assert stops if following is False, isinstance checks if value is an item of CardValue
        assert isinstance(suit, CardSuit)
        return tuple.__new__(cls, (value, suit))    #return tuple should be similar to self.value, self.suit

    @property   #i need to understand this...
    def value(self):
        return self[0]

    @property
    def suit(self):
        return self[1]

    def __str__(self):
        return "{}{}".format(str(self.value), self.suit.name)

    def __repr__(self):
        return(str(self))

    def __setattr__(self, *ignored):
        raise NotImplementedError

    def __delattr__(self, *ignored):
        raise NotImplementedError

class Deck: #holds all Card class Objects that are not drawn
    def __init__(self): #creates a new shuffled Deck containing all Cards
        self.cards = [
            Card(value, suit) for value in CardValue for suit in CardSuit
        ]
        #shuffle(self.cards)

    def setCard(self, value, suit): #tries to deal a specific  card from the deck    
        if Card(value, suit) in self.cards: #if successful returns the Card and removes from deck 
            self.removeCard(Card(value, suit).value, Card(value, suit).suit)
            return Card(value, suit)
        else:   
            print('not in deck')

    def topCard(self):
        cardone = self.cards.pop()
        #self.removeCard(cardone.value, cardone.suit)
        return(cardone)

    def removeCard(self, value, suit):  #tries to remove a specific Card from the deck // future dead cards
        if Card(value, suit) in self.cards:
            self.cards.remove(Card(value, suit))
        else:
            print('not in deck')

#this creates the dict in python
helpmemore = [] #temp array to store card combinations in
mylazydict = {} #dict to store arrays of card combinations in   "AK" : []
for valueone in CardValue:
    for valuetwo in CardValue:
        for suitone in CardSuit:
            for suittwo in CardSuit:
                if valueone != valuetwo or suitone != suittwo:  #no double cards
                    helpmemore.append((Card(valueone, suitone), Card(valuetwo, suittwo)))
        mylazydict[str(valueone)+str(valuetwo)] = helpmemore
        helpmemore = []

#this saves the dict to a file
dotdot = 0
input2_dict = open("input2_dict.py", "w")
input2_dict.write("input2_dict = {"+"\n")
for line in mylazydict:
    input2_dict.write("\t"+"\""+line+"\" : "+str(mylazydict[line]))
    if dotdot != len(mylazydict)-1:
        input2_dict.write(",")
    input2_dict.write("\n")
    dotdot += 1
input2_dict.write("\t}")
input2_dict.close()

错误:

  File "input2_dict.py", line 7                                                                                             "A9" : [(Ac, 9c), (Ac, 9d), (Ac, 9h), (Ac, 9s), (Ad, 9c), (Ad, 9d), (Ad, 9h), (Ad, 9s), (Ah, 9c), (Ah, 9d), (Ah, 9h), (Ah, 9s), (As, 9c), (As, 9d), (As, 9h), (As, 9s)],                                                                                      ^                                                                                                     SyntaxError: invalid syntax 

猜测是因为9和整数,并且仅取第一行我就得到了名称错误:

Traceback (most recent call last):                                                                                        File "input2_dict.py", line 2, in <module>                                                                                "AA" : [(Ac, Ad), (Ac, Ah), (Ac, As), (Ad, Ac), (Ad, Ah), (Ad, As), (Ah, Ac), (Ah, Ad), (Ah, As), (As, Ac), (As, Ad), (As, Ah)],                                                                                                            NameError: name 'Ac' is not defined 

然后我要检查dict条目中的卡是否仍在Deck.cards中

0 个答案:

没有答案