Python,从查找表运行函数

时间:2015-10-18 07:18:18

标签: python

我尝试通过将它们映射到查找表中的键来运行某些函数。我有一个列表lis,我遍历它并检查列表中的某些值是否与查找表中的键相同。如果他们是我想按照键运行该功能。 当我尝试运行下面时,它会打印所有3个,我不明白。

因为它应该只在我眼中打印1和2。

ops1 = {


        "1": print("1"),
        "2": print("2"),
        "4": print("4")
}

lis = [1, 2, 3]

for x in range(0, len(lis)-1):
    if (lis[x] in ops1.keys()):
        ops1.get(x)

2 个答案:

答案 0 :(得分:2)

让我们逐行完成。

ops1 = {
        "1": print("1"), # this value is actually the value returned by print
        "2": print("2"),
        "4": print("4")
} # when the dictionary is created, everything in it is evaluated,
# so it executes those print calls
# that's why you see all three printed

lis = [1, 2, 3]

for x in range(0, len(lis)-1): # this includes 0 and 1
    if (lis[x] in ops1.keys()): # lis[0] is 1 and lis[1] is 2
        ops1.get(x) # look for 0 and then 1 in the dictionary

现在让我们解决它。

ops1 = {
        "1": lambda: print("1"), # this value is now a FUNCTION, which you can call later
        "2": lambda: print("2"),
        "4": lambda: print("4")
} # when the dictionary is created, everything in it is evaluated, but the functions are not called

lis = [1, 2, 3]

for x in range(len(lis)): # goes through 0, 1, and 2
    if lis[x] in ops1: # lis[0] is 1, lis[1] is 2, lis[2] is 3
        ops1.get(str(lis[x]), print)() # look for '1', '2', and '3',
                                       # then call their values

你可以像这样改进最后一个循环:

for x in lis:
    ops1.get(str(x), print)()

所以,首先我们查找密钥'1'。这对应于一个功能。然后我们调用该函数。这将打印字符串'1\n'。然后我们查找键'2'。这对应于一个功能。然后我们调用该函数。这将打印字符串'2\n'。然后我们查找键'3'。这在字典中不存在,因此它返回默认函数。然后我们称之为默认函数。这将打印字符串'\n'

答案 1 :(得分:1)

试试这个(大致)

问题是您将调用print的结果分配给查询表。您想要分配功能定义,而不是调用它。然后在循环中调用lookupup函数。

def print1():
    print(1)

Ops = {
"1" : print1,
"2" : another_func,
...

}

for key in ["1","2","3"]:
    ops[key]()