There is a dictionary, where the key is the value that we later enter through Input, and the value of the dictionary is the name of the function. Separately, each function is performed for the list (it is generated randomly.) How to make that several functions are performed at the same time, which we enter via Input and then look for it in the dictionary?

Code snippet:

functions = {'sum': sum_list, 'multiply': multiply_list, 'join': join_list, 'union': union_list, 'reverse': reverse_list, 'negated': negated_list, 'inverted': inverted_list, 'squared': squared_list, 'odds': odds_list, 'evens': evens_list, 'simples': primenumbers_list} name = input("Выберите 'sum', 'multiply', 'join', 'union', 'reverse','negated' " "'inverted', 'squared','odds', 'evens', 'simples': ") reducer = functions[name] result = reduce(reducer, randlist) print(result) 

    1 answer 1

    Example:

     In [415]: lst = [0, 4, 0, 3, 8, 9, 1, 8, 0, 2] In [416]: from operator import methodcaller In [417]: functions = [min, max, sum] In [418]: list(map(methodcaller('__call__', lst), functions)) Out[418]: [0, 9, 35] 

    UPDATE:

    We enter 3 values ​​through input: sum, reverse, evens. We receive the sum (sum) of return values ​​(reverse), even numbers from the list (even). Value we get one

     def rev(lst): if isinstance(lst, (list, tuple)): return [1./x for x in lst] def evens(lst): return [x for x in lst if x%2 == 0] functions = [sum, rev, evens] def func(functions, arg): if len(functions) == 1: return functions[0](arg) return func(functions[:-1], functions[-1](arg)) 

    check:

     In [126]: lst = [1,2,3,4,5,6,7,8,9,10] In [127]: sum(1/x for x in lst if x%2 == 0) Out[127]: 1.1416666666666666 In [128]: func(functions, lst) Out[128]: 1.1416666666666666 
    • And if I need two functions to work simultaneously: for example, the sum of all inverse values ​​of numbers? - Verylucky333
    • @ Verylucky333, give a small example of input and output data in the question and examples of 2-3 functions - MaxU
    • We enter 3 values ​​through input: sum, reverse, evens. We receive the sum (sum) of return values ​​(reverse), even numbers from the list (even). Value we get one. - Verylucky333
    • @ Verylucky333, added option with recursive function ... - MaxU