我在代码中填充了数组,我想通过在函数参数中调用它的名称来访问它。 我不是很准确,我需要访问数组名称、和值。我只是把整个代码粘贴到你身上,也许我遗漏了什么:
#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)
另一种思考是:
或者
您可以将两个数组作为单独的参数传入,并在函数中使用它们:
如果必须将它们分组为单个函数参数,可以这样做:
用
myFunc(cars, sports)
调用函数应该可以正常工作。否则,代码似乎可以工作。你知道吗相关问题 更多 >
编程相关推荐