我是一名新程序员,在将新字典名称作为参数传递给函数时遇到问题。
我正在尝试创建一个函数,该函数将从网页中提取数据,并为主机名和整行数据的值创建字典键。有多个页面将主机名的共性作为键值,我将最终将它们合并在一行中。在
首先,我创建一个名为control
的列表,用作我要搜索的所有主机的密钥文件。然后我将值webpage
、delimiter
、和{
执行此操作时,似乎没有将字典的名称传递给函数。在
#open key file
f = open("./hosts2", "r")
control = []
for line in f:
line = line.rstrip('\n')
line = line.lower()
m = re.match('(^[\w\d]+)', line)
control.append(m.group())
# Close key file
f.close()
def osinfo(url, delimiter, name=None):
ufile = urllib2.urlopen(url)
ufile.readline()
name = {}
for lines in ufile.readlines():
lines = lines.rstrip("\n")
fields = lines.split(delimiter)
m = re.match(r'(?i)(^[a-z0-9|\.|-]+)', fields[1].lower())
hostname = m.group()
if hostname in control:
name[hostname] = lines
print "The length of osdata inside the function:", len(name)
osdata = {}
osinfo(‘http://blahblah.com/test.scsv’, ';', name='osdata')
print "The length of osdata outside the function", len(osdata)
输出如下:
^{pr2}$似乎该函数没有提取关键字。在
这是因为范围吗?在
应该传递对象
name=osdata
,而不是传递字符串name='osdata'
。在并且不要在函数中重新定义它:
name = {}
,否则将丢失对原始对象的引用。在必须读:How do I pass a variable by reference?
传递一个},就像没有传递
name
参数,然后在函数中使用{}
初始化{name
参数一样。在两个意见
如果要修改字典,请将其作为参数传递,而不是其名称
有一点你说得对:在Python中,如果作为参数传递的对象是可变的,那么位于外部范围内并作为参数传递的变量可以被函数修改(就像它是通过引用传递的,尽管对对象的引用是通过值传递的,see here)
相关问题 更多 >
编程相关推荐