如何将一个新的字典名作为参数传递给Python中的函数?

2024-10-08 19:19:43 发布

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

我是一名新程序员,在将新字典名称作为参数传递给函数时遇到问题。
我正在尝试创建一个函数,该函数将从网页中提取数据,并为主机名和整行数据的值创建字典键。有多个页面将主机名的共性作为键值,我将最终将它们合并在一行中。在

首先,我创建一个名为control的列表,用作我要搜索的所有主机的密钥文件。然后我将值webpagedelimiter、和{}传递给函数。
执行此操作时,似乎没有将字典的名称传递给函数。在

#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}$

似乎该函数没有提取关键字。在

这是因为范围吗?在


Tags: 数据函数namein名称字典lineopen
2条回答

应该传递对象name=osdata,而不是传递字符串name='osdata'。在

并且不要在函数中重新定义它:name = {},否则将丢失对原始对象的引用。在

>>> def func(name=None):
    name ={}         #redefine the variable , now reference to original object is lost
    return id(name)
... 
>> dic={}
>>> id(dic),func(dic)   #different IDs
(165644460, 165645684)

必须读:How do I pass a variable by reference?

传递一个name参数,然后在函数中使用{}初始化{},就像没有传递name参数一样。在

def osinfo(url, delimiter, name=None):
    ufile = urllib2.urlopen(url)
    ufile.readline()
    name = {}                               # you define name here as empty dict
        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)

两个意见

  • 如果要修改字典,请将其作为参数传递,而不是其名称

  • 有一点你说得对:在Python中,如果作为参数传递的对象是可变的,那么位于外部范围内并作为参数传递的变量可以被函数修改(就像它是通过引用传递的,尽管对对象的引用是通过值传递的,see here

相关问题 更多 >

    热门问题