简体   繁体   English

有什么办法可以将其更改为 for 循环吗? Python

[英]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:这是我使用 for 循环的代码:

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.在更新代码的第一个版本时,您可以编写自己的循环来做的唯一有用的事情是重做max已经做的事情。 That makes it extra odd that you're calling max yourself in the second version of your code.这让您在代码的第二个版本中自己调用max变得格外奇怪。 If you wanted to just use max , you wouldn't need your own loop!如果您只想使用max ,则不需要自己的循环!

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.请注意,您通常不想从循环内部return ,除非遇到需要您跳出并放弃循环的 rest 的情况。 You only want to do that in this program when you get an exception (returning -1 without processing the rest of the input).当您遇到异常(返回-1而不处理输入的 rest)时,您只想在此程序中执行此操作。 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).您的list变量不包含列表(它是一个字符串), idx也不包含索引(它是一个列表)。 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).如果您想通过迭代字典的.items()为键和值提供有意义的名称,只需在for循环中直接使用这些名称(但如果没有更好的名称, keyvalue也可以).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有什么办法可以压缩Python中的for-else循环吗? - Is there any way to condense a for-else loop in Python? 有什么方法可以用 python 中的相同项目循环迭代? - any way to loop iteration with same item in python? 有没有办法在 python 中使用带有 2 个变量的 for 循环? - Is there any way to use a for loop with 2 variables in python? Python 中是否有任何方法可以更改列的位置? - is there any way in Python to change the columns' positions? 有什么办法可以在Windows上更改Python安装路径吗? - Is there any way to change Python installation path on windows? 有什么办法可以更改 Python 中字典中的键(不是值)吗? - Is there any way to change the keys (not Values) in the dictionary in Python? 知道在Python中的for循环中是否还有任何要迭代的元素的更好方法 - Better way to know if there are any elements left to iterate in for loop in Python 有什么办法可以用更高效的python替换for循环 - Is there any way to replace a for loop with something more efficient in python 有什么方法可以在for循环中保存多个图而不在python中覆盖? - any way to save multiple plots in for loop without overwriting in python? 有没有办法在 Python for 循环中退回一步? - Is there any way to go back a step in a Python for-loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM