简体   繁体   中英

Problems with nested functions in Python

I'm having a simple problem using Python functions.

I'll try to be clear:

I have to write two functions:

The first one , returns a dictionary where the keys are names, associated to lists of 5 random numbers.

{'John': [25, 27, 30, 14, 15], 'Mary': [15, 26, 14, 31, 12], 'Saray': [27, 15, 19, 14, 39]}

This is an example of the output of the first function.

The second function, should return me a dictionary with the same keys, and the average of the five numbers of the lists. expected output:

{'John': [21.8], 'Mary': [19.6], 'Saray': [22.8]}

The problem is that, I don't know how the second function should take as input the results of the first one. I tried with something like that:

def First_Function(a):
    d={}
    [...]
    x=list(d.keys())
    y=list(d.values())
    return d

def Second_Function(a=x,b=y):

But the progrm says that x and y are not defined. What can i do?

x and y are valid variables only inside the first function.

Your first function is returning dictionary, pass that into second one.

Example:

def ex2(d):
    x = list(d.keys())
    y = list(d.values())
    # What ever your function does.

result = ex1(a)
ex2(d=result)  # I gave myself a freedom to name parameter d

Assuming you have dictionary generated by the first function

 import numpy as np

 def func_(a):
     for key, value in a.items():
        a[key] = [np.mean(a[key])]
     return a

func_(a)
#op
{'John': [22.2], 'Mary': [19.6], 'Saray': [22.8]}

If you're writing two separate functions. that is not nesting.

With two separate functions, this would be a valid way to do it:

def first_function(a):
    d={}
    [...]
    return d

def second_function (d: dict):
    result = {}
    for key in d:
        my_list = d[key]
        result[key] = sum(my_list)/len(my_list)
    return result

Output:

>>> second_function({'John': [25, 27, 30, 14, 15], 'Mary': [15, 26, 14, 31, 12], 'Saray': [27, 15, 19, 14, 39]})

{'John': 22.2, 'Mary': 19.6, 'Saray': 22.8}

You may want to modify the code to suit your expected output. However, I couldn't help but notice the average calculated for the "John" key in your question is wrong.

To nest the second function into the first one and have it be executed as a part of the first function, you can use this syntax:

def first_function(a):

    def second_function (d: dict):
        result = {}
        for key in d:
            my_list = d[key]
            result[key] = sum(my_list)/len(my_list)
        return result

    d={}
    [...]
    return second_function(d)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM