Python理解整合

tMC*_*tMC 1 python parsing list-comprehension

我觉得必须有一种更容易(更清晰)的方法来使用理解来解析linux上的meminfo文件.该文件的格式为:

MemTotal:        3045588 kB
MemFree:         1167060 kB
Buffers:          336752 kB
Cached:           721980 kB
SwapCached:            0 kB
Active:           843592 kB
Inactive:         752920 kB
Active(anon):     539968 kB
Inactive(anon):   134472 kB
Run Code Online (Sandbox Code Playgroud)

我试图重写for循环id用于使用理解,发现我需要3个...

def parse_mem_file(memfile = '/proc/meminfo'):
    lines = open(memfile, 'r').readlines()
    lines = [line.strip('kB\n') for line in lines if line[-3:] == 'kB\n']
    lines = [line.split(':') for line in lines]
    return dict((key, int(value)) for (key, value) in lines)

print parse_mem_file()
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?有没有合理的方法来简化这个?

GWW*_*GWW 6

d = {}
with open(f) as fin:
    for l in fin:
        x = l.split()
        d[x[0][:-1]] = int(x[1])
return d
Run Code Online (Sandbox Code Playgroud)