gpt4 book ai didi

python - 如何将新字典名称作为参数传递给 Python 中的函数?

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:06 25 4
gpt4 key购买 nike

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

首先,我创建了一个名为 control 的列表,用作我正在搜索的所有主机的 key 文件。然后,我将值 webpagedelimiterdictionary name 传递给函数。
这样做时,字典的名称似乎没有传递给函数。

#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)

输出如下:

$./test.py
The length of osdata inside the function: 11
The length of osdata outside the function: 0

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

这是因为范围吗?

最佳答案

不应传递字符串 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?

关于python - 如何将新字典名称作为参数传递给 Python 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16594080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com