列表理解是否会使以下代码更具可读性?

时间:2016-10-25 15:35:40

标签: python dictionary list-comprehension

我正在编写一个解析Linux审核的程序,需要在系统调用名和数字之间创建一个映射。系统调用来自/usr/include/asm/unistd_64.h并采用以下格式:

#define __NR_read 0
#define __NR_write 1
#define __NR_open 2
#define __NR_close 3

以下代码有效:

SYSCALLS = {}
SYSCALL_HEADERS="/usr/include/asm/unistd_64.h"

with open(SYSCALL_HEADERS) as syscalls:
    for line in syscalls:
        if  "_NR_" in line:
            sysc, syscn = re.split('_NR_| ', line.strip())[2:]
            SYSCALLS[syscn] = sysc

但似乎有点长啰嗦。有没有办法使用列表推导来缩短代码并使其更具可读性?

3 个答案:

答案 0 :(得分:3)

您可以使用dict理解来生成相同的输出:

with open(SYSCALL_HEADERS) as syscalls:
    SYSCALLS = {
        syscn: sysc 
        for line in syscalls if  "_NR_" in line
        for sysc, syscn in (re.split('_NR_| ', line.strip())[2:],)}

但我不认为那更具可读性。

答案 1 :(得分:0)

更短,但不一定更具可读性:

>>> dict(l.split("_")[3:][0].split(" ")[::-1] for l in f if "_NR_" in l)
{'1': 'write', '3': 'close', '0': 'read', '2': 'open'}

答案 2 :(得分:-1)

试试这个:

f = open("/usr/include/asm/unistd_64.h")    
SYSCALLS = {k:v for line in f.readlines()
            for k,v in (re.split('_NR_| ', line.strip())[2:],)
            if  "_NR_" in line}