python-3.x - 从日志文件中查找延迟最低的用户

我有一个输入文件,其中包含以下日志条目。

200,John,/home,60ms
200,Sarah,/log,13ms
500,Jack,/home,40ms

输出:

sarah

回答1

我假设,您的数据在 txt 文件中

file = "path/to/user_data.txt"

def find_lowest(file):
    with open(file, 'r') as f:
        # Create list that contains every latency 
        # Because you cannot know the lowest or the max latency before check them all
        latencies = [] 
        names = []
        # Make a loop through users'data
        for user_data in f.readlines():
            data = user_data.strip('\n').split(",")  # Convert a row (string) into list
            latencies.append(int(data[3][:-2]))  # [:-2] to remove "ms"
            names.append(data[1])

    return names[latencies.index(min(latencies))]  # Return the first occurence

它给出一个具有最低延迟的用户名,如果两个相等,则仅返回具有此延迟的第一个用户

如果您想要一个包含所有用户频率最低的列表,只需将最后一行替换为:

return [names[i] for i, lat in enumerate(latencies) if lat == min(latencies)]

相似文章

随机推荐

最新文章