列表理解会使下面的代码更具可读性吗?

2024-09-29 01:36:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序来解析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

但这似乎有点冗长。有没有一种方法可以使用列表理解来缩短代码并使其更具可读性?你知道吗


Tags: 代码inincludeusr系统lineopennr
3条回答

试试这个:

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}

您可以使用听写理解产生相同的输出:

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:],)}

但我不认为这是任何可读性。你知道吗

较短,但不一定更易读:

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

相关问题 更多 >