简体   繁体   中英

Is there any way to change this into a for loop? Python

My code gets a dictionary from the user and gets the average of the values in the dictionary, It must return the key on the list with the highest average. But I want to make it into a loop. I have written a code in the bottom but it is not working. My

def average(idx):
    return sum(idx) / len(idx)

def mylist(thekey):
        try:
            return max(thekey, key=lambda k: average(thekey[k]))
        except TypeError:
            return -1
thekey = {
        "list_1": [0, 6, 50000, 250],
        "list_2": [772277, 880008, 33300, 1000],
        "list_3": [100000000, 2555555, 2000, 2000]
        }
print(mylist(thekey))

This is my code using for loop:

def average(idx):
    return sum(idx) / len(idx)

def mylist(thekey):
    for key, value in thekey.items():
        if all(isinstance(value, int) for value in thekey.items()) == False:
            return -1
        else:
            list = key
            idx = value
            list_avg = {}
            x = average(idx)
            list_avg.update({list: x})
            for maximum in list_avg:
                return max(list_avg[maximum])
thekey = {
        "list_1": [0, 6, 50000, 250],
        "list_2": [772277, 880008, 33300, 1000],
        "list_3": [100000000, 2555555, 2000, 2000]
        }

print(mylist(thekey))

The only useful thing you can write your own loop to do in updating the first version of your code is to redo what max does already. That makes it extra odd that you're calling max yourself in the second version of your code. If you wanted to just use max , you wouldn't need your own loop!

Try:

def mylist(thekey):
    max_key = None
    max_avg = float('-inf') # negative infinity

    for key, value in thekey.items():  # only one loop needed for this
        try:
            avg = average(value)       # try to get an average
        except TypeError:
            return -1                  # if we can't, give up and bail out early

        if avg > max_avg:              # otherwise, compare with max so far
            max_key = key
            max_avg = avg

    return max_key                     # return only after the loop ends

Note that you generally don't want to return from inside of a loop unless you've encountered a condition that requires you to bail out and give up on the rest of the loop. You only want to do that in this program when you get an exception (returning -1 without processing the rest of the input). Otherwise, you need to wait until the end of the loop to return.

I did not replicate your renaming of all your variables in the loop body, since that was both unnecessary and extremely confusing. Your list variable did not contain a list (it was a string), nor did idx contain an index (it was a list). If you want to give meaningful names for the key and value from iterating on the .items() of a dictionary, just use those names directly in the for loop (but key and value are fine too, if there aren't any better names).

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