在带有跳转的字典中查找每个组中具有最小值的键(Python)

wlp8pajw  于 2023-06-04  发布在  Python
关注(0)|答案(2)|浏览(254)

我有一本字典,它的键会发生跳跃。我怎样才能在每个组之间找到值最小的键?例如,我有

myDict = {
        0.98:0.001,
        1.0:0.002,
        1.02: 0.0001,
        3.52:0.01,
        3.57:0.004,
        3.98: 0.005,
        4.01: 0.02,
        6.87: 0.01,
        6.90:0.02,
        6.98:0.001,
        7.0: 0.02
}

我想要的输出是1.02, 3.57, 6.98。我正在使用的实际字典有1000多个条目。

nkoocmlb

nkoocmlb1#

这里有一个解决方案,假设字典是根据键(代码注解中的解释)按升序排序的:

def main():
    d = {
        0.98: 0.001, 1.0: 0.002, 1.02: 0.0001,
        3.52: 0.01, 3.57: 0.004, 3.98: 0.005, 4.01: 0.02,
        6.87: 0.01, 6.90: 0.02, 6.98: 0.001, 7.0: 0.02
    }

    all_groups = []  # list to store the groups
    minimums = []  # list to store all mins
    # initializing holders for minimum key and value
    min_k = 1000
    min_v = 0

    for k, v in d.items():
        # an if-statement just to add the first group with key inside
        if len(all_groups) == 0:
            all_groups.append([k])
            min_k = k
            min_v = d.get(k)
        else:
            # check if the difference is less or equal to 1
            if k - all_groups[-1][-1] <= 1.0:
                all_groups[-1].append(k)

                # each time we add a key to a group, we check if it is the minimum
                if d.get(k) < min_v:
                    min_k = k
                    min_v = d.get(k)
            else:
                minimums.append((min_k, min_v))

                # we append a new list with the new key inside to `all_groups`
                # in which we will store the next elements
                all_groups.append([k])
                min_k = k
                min_v = d.get(k)

    minimums.append((min_k, min_v))  # adding last minimums because for loop ends without adding them

    for i in minimums:
        print(i[0])  # 1.02, 3.57, 6.98

if __name__ == "__main__":
    main()
x6yk4ghg

x6yk4ghg2#

您可以使用itertools.accumulate生成组编号,其中每次“跳转”都会使组编号增加1。然后使用itertools.groupby获取每个组中的第一个条目:

from itertools import accumulate,groupby

group  = accumulate(k-prev>1 for k,prev in zip(myDict,(min(myDict),*myDict)))
result = [k for _,(k,*_) in groupby(myDict,lambda _:next(group))]

print(result)
[0.98, 3.52, 6.87]

相关问题