我们可以根据elif else调用方法吗...例如:
if line2[1] = '1':
a(line2)
elif line2[1] = '2':
b(line2)
elif line2[1] = '3':
c(line2)
然后列表继续。 我们可以使用地图并调用该函数。说
线路输入示例:
line = [' 1','说','嗨']
line = [' 2',' How',' Are']
代码:
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)
如何根据输入调用函数。
如果可能,请发送示例代码
由于 拉克什
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]
是否也有解决方法。
答案 0 :(得分:5)
更新:一种棘手的方法
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)
答案 1 :(得分:1)
你有正确的想法,但是你有点错误 - 你应该传递一个函数对象,而不是调用它。
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 ..