簡體   English   中英

列表理解是否會使以下代碼更具可讀性?

[英]Will a list comprehension make the following code more readable?

我正在編寫一個程序來解析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

但是似乎有點長。 有沒有一種方法可以使用列表推導來縮短代碼並使代碼更具可讀性?

您可以使用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:],)}

但我認為這沒有任何可讀性。

較短,但不一定更具可讀性:

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

試試看:

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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM