从日志文件中查找延迟最低的用户

Find user with lowest latency from log file

我有一个包含以下完整日志的输入文件。

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

输出:

sarah

我假设,您的数据在一个 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只有第一个具有此延迟的用户

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

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