通过函数参数访问Pythons预定义的数组名称

2024-09-30 20:21:25 发布

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

我在代码中填充了数组,我想通过在函数参数中调用它的名称来访问它。 我不是很准确,我需要访问数组名称和值。我只是把整个代码粘贴到你身上,也许我遗漏了什么:

#the path of the dictionary txt files
dictionarypath = 'C:\\src\\'
#example files: qone.txt, adj.txt, subj.txt, gly.txt


#fill "dictionary-file-named" arrays to the words
dictnum=0
dictionaryfiles = []
for r, d, f in os.walk(dictionarypath):
    for file in f:
        if '.txt' in file:   
            dictname=(file[0:-4])
            dictionaryfiles.append(dictname)

            #getting the word from the files and put them into the named arrays (ex.: from subject.txt to subj[])
            dictfile = dictionarypath + dictionaryfiles[dictnum] + '.txt'

            with codecs.open(dictfile, encoding='latin1') as fp:

                line = fp.readline()
                vars()[dictname]=[] #set the actual array to empty first
                while line:
                    vars()[dictname].append(line.strip())
                    line = fp.readline()
            dictnum=dictnum+1   

#this generate the random sentence
def rstc(*pos): 
        for x in range(len(pos)):            
            actdictname=(pos[x])
            if len(actdictname) > 0:
                gennum=random.randrange(0, len(actdictname), 1)                
                sys.stdout.write(actdictname[gennum]+" ")

#qone -> question word (what)
#adj  -> adjectives
#subj -> subjects
#gly  -> glyps (!,.)

rstc(qone,adj,subj,subj,gly)


Tags: thetointxtlinefilesfileadj
3条回答

另一种思考是:

cars = ["Ford", "Volvo", "BMW"]
sports= ["Football", "Basketball", "Judo"]

def myFunc(what):
    print(eval(what[0])[0])# ->> prints out "Ford"
    print(eval(what[1])[1])# ->> prints out "Basketball"

myFunc(["cars", "sports"])

或者

def myFunc(what):
    print(what[0][0])# ->> prints out "Ford"
    print(what[1][1])# ->> prints out "Basketball"

myFunc(cars, sports)

您可以将两个数组作为单独的参数传入,并在函数中使用它们:

def myFunc(cars, sports):
    print(cars[0]) # ->> prints out "Ford"
    print(sports[1]) # ->> prints out Basketball

myFunc(cars, sports)

如果必须将它们分组为单个函数参数,可以这样做:

def myFunc(stacked_list):
   print(stacked_list[0][0]) # ->> prints out "Ford"
   print(stacked_list[1][1]) # ->> prints out Basketball

myFunc([cars, sports])

myFunc(cars, sports)调用函数应该可以正常工作。否则,代码似乎可以工作。你知道吗

相关问题 更多 >