为什么列表不生成元组列表?

2024-07-02 10:48:40 发布

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

我试着做一个宏来定义ctypes.结构. 宏如下所示:

(defmacro struct [name fields]
`(defclass ~name [ctypes.Structure]
    [-fields- 
    ~(lfor i (range 0 (len fields) 2)
        (tuple [
        (str (get fields (+ i 1)))
        (get fields i)))]))

我认为lfor表达式将生成一个元组列表,但是,当我使用macroexpand展开宏时,我发现生成的列表是一个列表列表,没有创建元组。宏扩展的结果如下:

=> (macroexpand '(struct Point [ctypes.c_int x ctypes.c_int y]))

HyExpression([
  HySymbol('defclass'),
  HySymbol('Point'),
  HyList([
     HySymbol('ctypes.Structure')]),
     HyList([
        HySymbol('-fields-'),
        HyList([
            HyList([
                HyString('x'),
                HySymbol('ctypes.c_int')]),
            HyList([
                HyString('y'),
                HySymbol('ctypes.c_int')])])])])

我很困惑,lfor表达式中的元组似乎根本不起作用。你知道吗


Tags: namefields列表get表达式ctypesstructurestruct
1条回答
网友
1楼 · 发布于 2024-07-02 10:48:40

由于我是一个海朗新手,我不熟悉的机制,宏观。经过几次尝试,我终于让它正常工作了,如下所示:

(defmacro compound [typename name fields]
`(defclass ~name [~typename]
    [-fields- 
    ~(lfor i (range 0 (len fields) 2)
        `(, 
            ~(str (get fields (+ i 1)))
            ~(get fields i)))]))

相关问题 更多 >