首页 > 解决方案 > 如何遍历整数列表,并引用字典中的最大键(所有整数),使其小于当前值?

问题描述

我有一本带有正整数的字典keys,这values对我的问题无关紧要。

另外,我正在遍历 a list of integers,并且我想引用字典中最大的键,它小于我在列表中迭代的当前整数(如果存在的话!)。

例如:

from collections import defaultdict
def Loep(obstacles):
    my_dict = defaultdict(int)
    output = []

    for i in range(len(obstacles)):

        if max(j for j in my_dict.keys() if j<= obstacles[i]):
            temp = max(j for j in my_dict.keys() if j<= obstacles[i])
            my_dict[obstacles[i]] = temp + 1
            output.append(my_dict[obstacles[i]])
        else:
            my_dict[obstacles[i]] = 1
            output.append(my_dict[obstacles[i]])
            
print(Loep([3,1,5,6,4,2]))

我收到上述错误-'if' statement我相信这是因为我有太多参数max(),有什么想法可以修改代码吗?

错误是:ValueError: max() arg is an empty sequence

我试过把它分开,但我做不到。

标签: pythonlistdictionary

解决方案


像这样的东西:

from collections import defaultdict

def Loep(obstacles):
    my_dict = defaultdict(int)

    my_dict.update({
        1: 0,
        2: 0,
        3: 0,
        4: 0,
        5: 0,
        6: 0,
    })
    output = []

    for obstacle in obstacles:
        keys = [j for j in my_dict.keys() if j <= obstacle]
        if keys:
            # there is at least one qualifying key
            key = max(keys)
            my_dict[obstacle] = key + 1
            output.append(my_dict[obstacle])
        else:
            my_dict[obstacle] = 1
            output.append(my_dict[obstacle])

    return output

print(Loep([3, 1, 5, 6, 4, 2]))

回应您关于在一行中执行此操作的评论.. 是的,您可以像这样浓缩它:

    for obstacle in obstacles:
        key = max([None]+[j for j in my_dict.keys() if j <= obstacle])
        if key is not None:
            # etc

..肯定还有其他方法可以做到这一点..使用过滤器..或其他方式..但是一天结束时,您不仅要获得最大值,还要使最大值低于特定值。除非您正在处理大量数据,或者需要极速……这是最简单的方法。


推荐阅读