![](/img/trans.png)
[英]How to pass numeric dictionary keys (formal parameter **name) to a python function?
[英]How do I pass a new dictionary name as a parameter to a function in Python?
我是一個新的程序員,我遇到了將新的字典名稱作為參數傳遞給函數的問題。
我正在嘗試創建一個函數,該函數將從網頁下拉數據並為主機名創建字典鍵和整行數據的值。 有多個頁面具有主機名的通用性作為鍵值,我最終將它們連接在一起。
首先,我創建一個名為control
的列表,用作我正在搜索的所有主機的密鑰文件。 然后我將值webpage
, delimiter
和dictionary 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)
必讀: 我如何通過引用傳遞變量?
你傳遞一個name
參數,然后初始化name
與{}
任何使用之前你的函數里面name
:好像沒有name
ARG傳遞。
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中,如果作為參數傳遞的對象是可變的,那么生活在外部范圍內並作為參數傳遞的變量可以被函數修改(就好像它通過引用傳遞,盡管更准確通過值傳遞對象的引用, 請參見此處 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.