简体   繁体   English

如何从特定的SUBKEY中找到最低正值的顶级KEY?

[英]How do I find the top level KEY of the lowest positive VALUE from a particular SUBKEY?

My data looks like this: 我的数据如下所示:

{   
    'test1462477941.log': {   'end_diff': 537,
                               'file_epoch': 1462477941,
                               'start_diff': -33},
    'test1462478161.log': {   'end_diff': 317,
                               'file_epoch': 1462478161,
                               'start_diff': 284},
    'test1462478346.log': {   'end_diff': 132,
                               'file_epoch': 1462478346,
                               'start_diff': 99},
}

What I want to do is find the lowest, positive "start_diff" value in any of the keys and print the relative top level key (the filename). 我想做的是找到任何键中最低的正“ start_diff”值,并打印相对的顶级键(文件名)。 The data structure is throwing me off a bit though. 数据结构让我有点失望。

If using the data above, it shoud find and print out: 如果使用上述数据,则应查找并打印出:

test1462478346.log

Is there an elegant way to do this? 有没有一种优雅的方法可以做到这一点? If not, I'll take anything 如果没有,我会采取任何措施

Use filter for removing non positive and min with key for search: 使用filter删除非正数和min带搜索key

a = {
    'test1462477941.log': {'end_diff': 537,
                           'file_epoch': 1462477941,
                           'start_diff': -33},
    'test1462478161.log': {'end_diff': 317,
                           'file_epoch': 1462478161,
                           'start_diff': 284},
    'test1462478346.log': {'end_diff': 132,
                           'file_epoch': 1462478346,
                           'start_diff': 99},
}

only_positive_start_diff = filter(lambda x: x[1]['start_diff'] > 0, a.items())
min_start_diff = min(only_positive_start_diff, key=lambda x: x[1]['start_diff'])

print min_start_diff[0]  # Min log file

Without lambda it's look like: 没有lambda它看起来像:

def only_positive(x):
    return x[1]['start_diff'] > 0

def min_start(x):
    return x[1]['start_diff']

only_positive_start_diff = filter(only_positive, a.items())
min_start_diff = min(only_positive_start_diff, key=min_start)

print min_start_diff[0]

This is a solution using built-in function reduce : 这是使用内置功能reduce的解决方案:

import sys
filename, start_diff = reduce(
    lambda curMin, item:
        curMin if item[1]['start_diff']<0 or item[1]['start_diff']>curMin[1] else (item[0], item[1]['start_diff']),
    inputDict.iteritems(),
    ('not_found.log', sys.maxint))

print filename

Please note that the code is written with Python 2.7. 请注意,该代码是使用Python 2.7编写的。 If you use Python 3.x, then you should find reduce function in functools , and dict.iteritems() has been changed to dict.items() . 如果使用Python 3.x,则应该在functools中找到reduce函数,并且dict.iteritems()已更改为dict.items()

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

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