否则,Python 函数调用或方法调用



我们可以调用基于ifif其他方法的方法吗?例:

if line2[1] = '1': 
    a(line2) 
elif line2[1] = '2': 
    b(line2) 
elif line2[1] = '3': 
    c(line2)

这样的例子不胜枚举。我们可以使用地图并调用函数吗?说

线路输入示例:

行 = ['1','说','嗨']

行 = ['2','如何','是']

法典:

def g(line)
   my_map = { '1': a(line),
           '2': b(line),
           '3': c(line, b),
           ......
           and the list goes on
           }

   here if line[0] = '1' call a(line)
        elif line[0] = '2' call b(line)

如何根据输入调用函数。

如果可能,请发送示例代码

谢谢拉克什


行 = ['1','说','嗨','''

,''',....持续5-15次]在与上面相同的示例中,如果我还必须分配其他变量。我该怎么做。

if line2[1] == '8':
             p.plast = line2[3]
             p.pfirst = line2[4]
             p.pid = line2[9]
elif line2[1] == 'I':
             p.slast = line2[3]
             p.sfirst = line2[4]
             p.sid = line2[9]
 elif line2[1] == 'Q':
            p.tlast = line2[3]
             p.tfirst = line2[4]
             p.tid = line2[9]

有没有解决方法。

更新:一个棘手的方法

def make_change(line, p):
    # Each value of the dict will be another dict in form property:index.
    # Where property is key of p object to be set/updated, index is index of line with which property should be updated.
    another_map = {
        "V": {'vlast': 3, 'vfirst': 5, 'vnone': 7},
        "S": {'slast':2, 'sfirst':9, 'snone':4}
    }
    val = another_map.get(line[1], None)
    if val is not None:
        # iterating over val items to get which property to set and index if line to set
        for key, item in val.iteritems():
            p[key] = line[item]
    print p

new_list = ["V", "S", 1,2,3,4,5,6,7,8,9,10,11,12,13]
make_change(new_list, {})

现在更改new_list[1]端查看输出


if line2[1] = '1': 
    a(line2) 
elif line2[1] = '2': 
    b(line2) 
elif line2[1] = '3': 
    c(line2)

将完美地工作。

但是你的第二种方法不起作用,因为当你写my_map = { '1': a(line), ... }时,my_map['1']None或返回函数的值(因为你正在调用函数(

试试这个

def g(line):
    # Note that value of dict is only the name of the function.
    my_dict = {
      '1': a,
      '2': b
      ...
    }
   # Assuming line[0] is 1,2,3, etc. Check if corresponding function exists in map_dict 
   # Convert line[0] to string before passing it in dict.get() method
   call_func = my_dict.get(str(line[0]), None)
   if call_func is not None:
        call_func(line)

你有正确的想法,但你有点错了——你应该传递一个函数对象,而不是调用它。

def g(line):
    my_map = {'1': a, '2': b, '3': c ... }
    cur_func = my_map.get(line)
    if cur_func is not None:
         cur_func(line)
    else:
         #No mapping found ..

最新更新