Python 中根据字符串行首执行不同函数

我们希望编写一个 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值