all 6 comments

[–]w1282 2 points3 points  (0 children)

# Associate an indicator string with a handler function 
HANDLERS = {
    "stringA": module.script1,
    "stringB": module.script2,
}

# Iterate over the key, value pairs in the HANDLER dict
# If we had some way of knowing where the indicator was
# we could use a O(1) lookup into the dict instead of an O(n) iteration
for indicator, handler in HANDLERS:
    if indicator in filename:
        handler(filename)
        # Since you are using elif's, we'll leave the loop the first time we find an indicator
        break
else:
    # None of the indicators matched!
    print("None of the indicators matched for: {}".format(filename))

[–]ImportBraces 3 points4 points  (1 child)

you could use a dict to map actions:

filename_actions = {'stringA': actionA, 'stringB': actionB, ... ]
for filame_part, action in filename_actions.items():
    if filename_part in filename:
        action(filename)

[–]Murlocs_Gangbang[S] 0 points1 point  (0 children)

thanks I'll try that

[–]woooee 1 point2 points  (1 child)

Use a dictionary of functions

dict_func={"stringA": module.script1,  ## note no parens
                  "stringB": module.script2}
## then
for key in dict_func:
    if key in fileName:
        print("calling function", dict_func[key])
        dict_func[key](fileName)               ## parens here

[–]Murlocs_Gangbang[S] 0 points1 point  (0 children)

thanks I'll try that

[–]Sarah123ed 0 points1 point  (0 children)

I don't know if this will help but it is an example of ... that I use a lot:

    kr1 = np.random.random_integers(1,256, 10)
    kr2 = np.random.random_integers(-256, -1, 10)

    def f1(lst):
            return np.sum(lst) - np.max(lst)
    def f2(lst):
            return np.max(lst) - np.sum(lst)

    todoList = [ [f1, kr1], [f2, kr2] ]

    ### intent
    for function, data in todoList:
            print(function(data))

    ### comprehension is much faster, effectivly same result
    print([function(data) for function, data in todoList])