我吃泡菜有问题

2024-09-30 06:18:55 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,当我只是涉猎编码和实验的时候,我想为我的D&;D运动需要

事实证明,在不理解代码的情况下将代码拼凑在一起并不总是有效的,令人震惊

所以,这是我的代码,虽然我确信它会让你的眼睛流血,但我只需要让它工作:

#import pickle
import pickle

#NPC ID generator 
counter=1
NPCS=[]
while counter<=170 :
    NPCS.append(counter)
    counter+=1


if len(NPCS)==170:
    print ("True")
else :
    print ("False") ; raise SystemExit 

#Attributes
name=[] ; occupation=[];weakness=[];need=[];desire=[];enemy=[];rumor=[];secret=[];passion=[]
redeemdamningquality=[];happy=[];occdesire=[];occcomplication=[];pcopinion=[];accomplish=[]
magical=[];politinfl=[];resource=[];intel=[];research=[]

NPCatt=[name,occupation,weakness,need,desire,enemy,rumor,secret,passion,redeemdamningquality,happy,occdesire,occcomplication,pcopinion, accomplish,magical,politinfl,resource,intel,research]  

#open a pickle file
newfile = 'NPCatt.pk'
#load your data back to memory when you need it
with open(newfile, 'rb') as fi:
  NPCatt = pickle.load(fi)

# Data Input 
print ("Enter the numerical code of the NPC you wish to modify")
raw=int(input())

if raw != ValueError :
    print ("Enter Name of NPC" + str(raw) ) ; a=input()
    if a!="":
        name.insert(raw+1,a);print ("Name Inserted Successfully")
    else:
        print ("Skipped!")

    print ("Enter Occupation of NPC" + str(raw) ) ;a=input()
    if a!="":
        occupation.insert(raw+1,a);print("Occupation Inserted Successfully")
    else:
        print ("Skipped!")
else :
    print ("BAD VALUE")

for x in (NPCatt) :
    if len(x)!=0 :
         print (x)
    elif len(x)>=170:
        print (x) ; print ("Has too many items")
    else :
        print (str(x) + "is empty")




with open(newfile, 'wb') as fi:
  # dump your data into the file
  pickle.dump(NPCatt, fi)

我不确定的是为什么我输入的数据在代码运行之间没有“保存”。 请帮忙


Tags: 代码namerawlenifcounterneedelse
2条回答

我知道这根本不是你想要的,但是你使用电子表格不是更容易吗

您正在手动输入数据并将其填充到二维数据结构中。
如果需要在其他地方使用数据,请将电子表格另存为.csv文件并导入该文件

你的问题是你对变量和任务如何工作的理解。在下面的代码中,您创建了许多列表。然后创建一个名为NPCatt的变量,该变量引用您创建的所有这些列表

#Attributes
name=[] ; occupation=[];weakness=[];need=[];desire=[];enemy=[];rumor=[];secret=[];passion=[]
redeemdamningquality=[];happy=[];occdesire=[];occcomplication=[];pcopinion=[];accomplish=[]
magical=[];politinfl=[];resource=[];intel=[];research=[]

NPCatt=[name,occupation,weakness,need,desire,enemy,rumor,secret,passion,redeemdamningquality,happy,occdesire,occcomplication,pcopinion, accomplish,magical,politinfl,resource,intel,research]

因此,如果我看NPCatt[0],它将是一个所有npc名称的列表。这很好。然而,你继续做下去

with open(newfile, 'rb') as fi:
  NPCatt = pickle.load(fi)

现在变量NPCatt并不指向所有列表。它现在指向未勾选的对象。因此,当您稍后执行names.append时,它将更新名称列表,但NPCatt不再指向此列表。因此,当你腌制NPCatt时,只需腌制你从文件中加载的内容

这是你错误的症结所在。如果您想在取消勾选后修改NPCatt保存的数据,那么您应该像这样访问它

   if a!="":
        NPCatt[0].insert(raw+1,a);print ("Name Inserted Successfully")
    else:
        print ("Skipped!")

    print ("Enter Occupation of NPC" + str(raw) ) ;a=input()
    if a!="":
        NPCatt[1].insert(raw+1,a);print("Occupation Inserted Successfully")
    else:
        print ("Skipped!")

然而,这变得非常混乱,不清楚哪个列表正在更新,因为您必须按索引位置引用它。您最好在这里查看python字典,因为您可以通过名称而不是索引位置来引用内容。或者,如果你准备创建一个NPC类,然后通过NPC\u ID:NPC\u class\u实例将每个NPC存储在dict中,那就更好了

更新

下面是一个简单的例子,我用一个npc类和一个dict按id存储npc。这只是一个简单的例子,没有任何关于设计或pro和con的真实想法,只是为了给大家展示一个例子

# import pickle
import pickle
npcs_pickle_file = 'NPCatt.pk'
npc_count = 170

class NPC:
    def __init__(self, name="", occupation="", weakness="", need="", desire="", enemy="",
                 rumor="", secret="", passion="", redeem_damning_quality="", happy="",
                 occ_desire="", occ_complication="", pc_opinion="", accomplish="", magical="",
                 politinfl="", resource="", intel="", research=""):

        # Attributes
        self.name = name
        self.occupation = occupation
        self.weakness = weakness
        self.need = need
        self.desire = desire
        self.enemy = enemy
        self.rumor = rumor
        self.secret = secret
        self.passion = passion
        self.redeem_damning_quality = redeem_damning_quality
        self.happy = happy
        self.occ_desire = occ_desire
        self.occ_complication = occ_complication
        self.pc_opinion = pc_opinion
        self.accomplish = accomplish
        self.magical = magical
        self.politinfl = politinfl
        self.resource = resource
        self.intel = intel
        self.research = research

    def __str__(self):
        npc_output = "####NPC SUMMARY####\n"
        for att, val in self.__dict__.items():
            if val:
                npc_output += (f"{att} = {val}\n")
        return npc_output

# open a pickle file
# load your data back to memory when you need it
try:
    with open(npcs_pickle_file, 'rb') as fi:
        npcs = pickle.load(fi)
except FileNotFoundError as fne:
    #file doesnt exist prob first time running so create a dict with the 170 npc id's
    npcs = {id: None for id in range(npc_count)}


#select an NPC to modify / create
npc_id = None
while not npc_id:
    try:
        npc_id = int(input(f"Enter the id number of the NPC you wish to modify: "))
    except ValueError as ve:
        print("You must provide a numerical id")

    if npc_id < 0 or npc_id >= npc_count:
        npc_id = None
        print(f"you must provide a value between 0 and {npc_count}")

name = input("Enter name of NPC: ")
occupation = input("Enter NPC occupation: ")

if npcs[npc_id]:
    npc = npcs[npc_id]
    print(npc)
    modify = input("This NPC already exists do you want to continue and change them? (y/n): ")
    if modify.lower() == "y":
        npc.name = name
        npc.occupation = occupation
else:
    npcs[npc_id] = NPC(name=name, occupation=occupation)

print(npcs[npc_id])
with open(npcs_pickle_file, 'wb') as fi:
    # dump your data into the file
    pickle.dump(npcs, fi)

相关问题 更多 >

    热门问题