我们希望编写一个 Python 函数,该函数读取字符串,并根据每行的第一个单词执行不同的函数。
以下是一个示例字符串:
host / yes / 7200
network / yes / 6000
applications / no / 6500
我们希望该函数能够根据每行的第一个单词,执行以下函数:
- host:打印出该行的第二个和第三个单词
- network:打印出该行的第二个和第三个单词
- applications:打印出该行的第二个和第三个单词
然而,我们尝试了以下代码,但发现它没有执行任何操作:
conf_list='''
host / yes / 7200
network / yes / 6000
applications / no / 6500
'''
list_conf={}
k=0
for line in conf_list.splitlines():
list_conf[k]=line
#print(list_conf[k])
if list_conf[0] == 'host':
print(list_conf[1], list_conf[2]) #output i wanted: yes 7200
elif list_conf[0] == 'network':
print(list_conf[1], list_conf[2]) #output: yes 6000
elif list_conf[0] == 'applications':
print(list_conf[1], list_conf[2]) #output: no 6500
Maybe these if and elif are not good?
我们怀疑问题可能出在 if 和 elif 语句上。
2、解决方案
我们可以使用以下几种方法来解决这个问题:
方法1:使用字典来存储函数
我们可以使用字典来存储函数,然后根据字符串行首的单词来获取相应的函数并执行。
def call_host(*args):
print args
def call_network(*args):
print args
def call_applications(*args):
print args
functions = {
'host': call_host,
'network': call_network,
'applications': call_applications,
}
for line in conf_list.splitlines():
line = line.strip()
if not line:
continue
try:
# handle arbitrary whitespace
func_name, truth, value = [ i.strip() for i in line.split('/') ]
value = int(value)
except ValueError:
# get here for incorrect number of items or the failure to make the value an int
print "Malformed line:", line
continue
function = functions.get(func_name, None)
if function is None:
print "Unknown function:", line
continue
function(truth, value)
方法2:使用 eval() 函数来执行字符串
我们可以使用 eval() 函数来执行字符串,从而实现根据字符串行首的单词来执行不同的函数。
conf_list='''
host / yes / 7200
network / yes / 6000
applications / no / 6500
'''
for line in conf_list.splitlines():
line = line.strip()
if not line:
continue
try:
func_name, truth, value = line.split('/')
value = int(value)
except ValueError:
# get here for incorrect number of items or the failure to make the value an int
print "Malformed line:", line
continue
try:
eval(func_name + '("' + truth + '", ' + str(value) + ')')
except NameError:
print "Unknown function:", line
continue
方法3:使用 exec() 函数来执行字符串
我们可以使用 exec() 函数来执行字符串,从而实现根据字符串行首的单词来执行不同的函数。
conf_list='''
host / yes / 7200
network / yes / 6000
applications / no / 6500
'''
for line in conf_list.splitlines():
line = line.strip()
if not line:
continue
try:
func_name, truth, value = line.split('/')
value = int(value)
except ValueError:
# get here for incorrect number of items or the failure to make the value an int
print "Malformed line:", line
continue
try:
exec(func_name + '("' + truth + '", ' + str(value) + ')')
except NameError:
print "Unknown function:", line
continue